3

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?

3
  • "something isnt quite right with it" - like what? Commented Feb 23, 2011 at 12:43
  • I'd also suggest string input = reg.Replace(input, ""); (or String.Empty if you like it better). It is very curious you've found the callback variation before a simple string replace... Commented Feb 23, 2011 at 12:48
  • You have shown an assumed the string to start, but could you show what you want the result to be? for example: do you want it to be 10,11,12,13,14,66 so removing ABC,DEF,GHI, Commented Feb 23, 2011 at 12:50

4 Answers 4

9

Do you just want a ^ in that?

input = Regex.Replace(input, @"[^0-9,]+", "");
Sign up to request clarification or add additional context in comments.

6 Comments

Perhaps he want to delete the commas of the deleted substrings... AB,CD,12,EF,GH => 12, (or perhaps even 12)
@xanatos - so make it something like @"([^0-9,]+,)" instead. Oh, gotta love regular expression syntax.
@xanatos - that goes into the wild speculation category, but you can trim excess commas on the next step.
@Michael - digits and letters might be mixed, according to the current code: a12v3,7y8z -> 123,78. If it isn't, it is much simpler - you can dimple match for all [0-9]+. Also, your regex requires a comma, it will not work on the last word (though that one is simple).
Thanks that did the trick - I previously also tried ^[0-9,]. Many thanks
|
1

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(',');

1 Comment

you could replace \d+ with [A-Za-z]+ if you just wanted the letters.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.