开发者

C# regular expression (replace)

开发者 https://www.devze.com 2023-02-12 16:54 出处:网络
Assume I have the string开发者_如何学运维: 10,11,12,13,14,ABC,DEF,GHI,66 I am looking to run a regex against it to only return 0-9 and the \",\" characters, essentially stripping anything else out

Assume I have the string开发者_如何学运维:

10,11,12,13,14,ABC,DEF,GHI,66

I am looking to run a regex against it to only return 0-9 and the "," characters, essentially stripping anything else out.

I have looked at Regex.Replace, but something isn't quite right with it. My code below:

Regex reg = new Regex(@"[0-9,]+");
string input = reg.Replace(input, delegate(Match m)
                {
                    return String.Empty;
                });

How can I make this work?


Do you just want a ^ in that?

input = Regex.Replace(input, @"[^0-9,]+", "");


Would a match collection give you more control?

Using \d+[^,] you can get a collection of digits?

You could then loop through your collection and recreate your desired string.

using linq you could do the following:

var input = "10,11,12,13,14,ABC,DEF,GHI,66";
Regex re = new Regex(@"\d+[^,]");
input = (from Match m in re.Matches(input) select m.Value).Aggregate("", (acc, item) => acc + "," + item).TrimStart(',');


How about this:

var testString = "10,11,12,13,14,ABC,DEF,GHI,66";
var split = testString.Split(',');
var result = String.Join(",", split.Where(element => element.All(c => Char.IsDigit(c))).ToArray());


I think that you may do it without regular expressions via analysis of what is required for your characters in set [0123456789,].

0

精彩评论

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