C # regex (replace)

Suppose I have a line:

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

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

I looked at Regex.Replace, but there is something wrong with it. My code is below:

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

How can I do this job?

+3
source share
4 answers

Do you want just ^that?

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

Will a collection of matches give you more control?

Using \d+[^,], can you get a set of numbers?

Then you can scroll through your collection and recreate the desired line.

using linq, you can 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(',');
+1
source

, , [0123456789,].

0

:

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());
0

Source: https://habr.com/ru/post/1794127/


All Articles