How do I use the C# Regular Expression object to make this substitution?
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!
Regex.Replace(source, @"(\d+\.\d+)m", "$1");
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.
Regex re = new Regex(@"(\d+\.\d+)m");
foreach (Match m in re.Match(str))
m.Groups[1]; //will contain ###.###
精彩评论