开发者

Regex to only allow first occurrence of character

I have some forms in which users will input some numbers, I want to prevent them from entering more than one comma in this string

I made somet开发者_运维百科hing like this

var input = "1,,,,2";
var value = Regex.Replace(input, ",{1,}", ".");

This will output 1.2, which is correct. But if I enter

var input = 1,,,2,3,,,4,5,,6

everything fails

What id like to do is to form the last version of the input to 1.23456

Any advice?

Thanks


Regex.Replace (input, @"(?<=^\d+),", ".").Replace (",", "");

This replaces the first , comma with a . period, then replaces the remaining commas with empty.


Use this regex: (?<!,[^,]*?),+

var res = Regex.Replace(input, @"(?<!,[^,]*?),+", ".").Replace(",", string.Empty);

Or this code:

var res = Regex.Replace(input, @"(?<!,[^,]*?)(,+)|(,+)", 
    m => m.Groups[1].Success ? "." : string.Empty);

Output: 1.23456

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜