Regex delete all (non numeric period OR)

I need a text like "joe ($ 3,004.50)" that will be filtered to 3004.50 but terrible in regular expression and cannot find a suitable solution. Therefore, only numbers and periods should remain - everything else is filtered. I am using C # and VS.net 2008 framework 3.5

+61
c # regex
Jun 16 '10 at 17:35
source share
5 answers

This should do it:

string s = "joe ($3,004.50)"; s = Regex.Replace(s, "[^0-9.]", ""); 
+118
Jun 16 '10 at 17:38
source share

Regular expression:

 [^0-9.] 

You can cache the regex:

 Regex not_num_period = new Regex("[^0-9.]") 

then use:

 string result = not_num_period.Replace("joe ($3,004.50)", ""); 

However, you should keep in mind that in some cultures there are different conventions for writing sums of money, for example: 3.004.50.

+25
Jun 16 '10 at 17:37
source share

For the accepted answer, MatthewGunn raises the point that all digits, commas and periods in the entire line will be brought together. This will avoid this:

 string s = "joe.smith ($3,004.50)"; Regex r = new Regex(@"(?:^|[^w.,])(\d[\d,.]+)(?=\W|$)/)"); Match m = r.match(s); string v = null; if (m.Success) { v = m.Groups[1].Value; v = Regex.Replace(v, ",", ""); } 
+2
Dec 04 '15 at 8:34
source share

The approach to removing abusive characters is potentially problematic. What if there is more in the line . ? It will not be deleted, although it should!

Deleting non-digital digits or periods the string joe.smith ($3,004.50) converted to .3004.50 .

Imho, it's better to map a specific pattern and extract it using a group. It would be simple to find all adjacent commas, numbers and periods with a regular expression:

 [\d,\.]+ 

Test run example:

 Pattern understood as: [\d,\.]+ Enter string to check if matches pattern > a2.3 fjdfadfj34 34j3424 2,300 adsfa Group 0 match: "2.3" Group 0 match: "34" Group 0 match: "34" Group 0 match: "3424" Group 0 match: "2,300" 

Then, for each match, remove all the commas and send them to the parser. To handle a case with something like 12.323.344 , you can do another check to see that the corresponding substring has at most one . .

0
Dec 03 '15 at 9:20
source share

You are dealing with a string - this is an IEumerable<char> , so you can use LINQ:

 var input = "joe ($3,004.50)"; var result = String.Join("", input.Where(c => Char.IsDigit(c) || c == '.')); Console.WriteLine(result); // 3004.50 
0
Dec 07 '15 at 19:54
source share



All Articles