开发者

Regex to only allow first occurrence of character

开发者 https://www.devze.com 2023-03-17 05:32 出处:网络
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 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

精彩评论

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

关注公众号