tags:

views:

88

answers:

3

I am writing a method to take a DevExpress "filter" string and convert it to a useable SQL string. For the most part this is easy with simple string substitutions here or there. One thing, however, has me scratching my head because I've just not taken the time to learn Regular Expressions in C#/.NET.

When a decimal number is used, DevExpress emits a string like "FieldName > 2.0m". The problem is the decimal signifier, "m" at the end of the number. I need to take all substrings of the format ###.###m and change them to ###.### (where the number of digits is variable). If I remember correctly, matching this number would be something like:

[0-9,.]* 

But how do I look for a number with the "m" at the end and how do I use the Regex class to generate a new string with the m removed?

Thanks!

+3  A: 

This will match strings following this pattern - one or more number, followed by a ., followed by one or more number, followed by an m:

\d+\.\d+m

See this handy cheat sheet.

In order to be able to refer to the original number (without the m), you need to capture the match (captured group) for a back reference using ():

(\d+\.\d+)m

This will now allow you to replace:

RegEx.Replace(source, @"(\d+\.\d+)m" ,"$1");

The $1 refers to the first captured group.

Oded
+1 for the cheat sheet.
JonH
+1 for the cheat sheet and for the explanation of the captured group and the back reference.
Mark Brittingham
+2  A: 
Regex re = new Regex(@"(\d+\.\d+)m");
foreach (Match m in re.Match(str))
   m.Groups[1]; //will contain ###.###
Andrey
+3  A: 
Regex.Replace(source, @"(\d+\.\d+)m", "$1");
Adam Ruth
I know little `.NET` regex: what does `(?` followed by `(` mean? In most regex flavours I know, it is invalid syntax. EDIT: ah, you forgot the `:`... In which case you mind as well do: `@"(\d+\.\d+)m"`
Bart Kiers
Yeah, but then I realised that I didn't need it at all!
Adam Ruth
Well, never too late to edit, right?
Bart Kiers
You should also be able to use positive lookahead to match the decimal but mot the trailing 'm': @"\d+[\.,]\d+(?=m)".
leson
Thanks Adam - that worked and makes sense...
Mark Brittingham