-4

I have a string, something like this: rgb (255, 0, 0). And I want to remove every character inside it except numbers and the , (comma) character.

I have two questions based on this:

  1. How to do that with Regex? (I found this answer, but I don't know how to include the , (comma) sign into it...)

  2. Is Regex the best method for this purpose? Or there is some other (better) methods?

(Best = having best performance)

Community
  • 1
  • 1
Mahdi Ghiasi
  • 14,873
  • 19
  • 71
  • 119

3 Answers3

8

Regex is the easiest, surely:

Regex.Replace(s, "[^\d,]+", "")

will replace everything that is not a digit or a comma.

Joey
  • 344,408
  • 85
  • 689
  • 683
3

Use the same approach as in the question you referenced:

Regex rgx = new Regex("[^\d,]");

str = rgx.Replace(str, string.Empty);
Community
  • 1
  • 1
Bernard
  • 7,908
  • 2
  • 36
  • 33
1

Regex is a very viable solution.

I would set my pattern to (?<colour>(\d*), ?(\d*), ?(\d*)) allowing for optional spaces before each colour digit but does not limit to maximum 3 numbers per digit (a further tweak could rectify this).

You would then access the colour as a group.

Regex pattern = new Regex(@"(?<colour>(\d*), ?(\d*), ?(\d*))");
Match m = pattern.Match(color);
Console.WriteLine(m.Groups["colour"].ToString());

Returns: 255, 0, 0

Lewis Harvey
  • 332
  • 2
  • 10
  • After viewing the question, I see performance was a requirement so I test the two and the results are not what I expected. Regex replace is faster up to 8 times! Full test code can be found at http://lewisharvey.wordpress.com/2012/08/29/regex-replace-vs-regex-match-and-group-performance/ – Lewis Harvey Aug 29 '12 at 15:48
  • Performance test results location changed: http://justcodesomething.wordpress.com/2012/08/29/regex-replace-vs-regex-match-and-group-performance/ – Lewis Harvey Dec 05 '13 at 08:51