.NET Framework Bookmark and Share   
 index > Regular Expressions > Capturing a named group - currency
 

Capturing a named group - currency

I am trying to capture a money amount using Regex using named groups.

so I have the following code:

string line1 = "Total $19 | Subtotal $0.75";
Regex r = new Regex(@"Total \$(?<total>\d+\.?\d{0,2}?) \| Subtotal \$(?<sub>\d+\.?\d{0,2}?)");
Match m = r.Match(line1);
Assert.IsTrue(m.Success);
Assert.AreEqual(19, Convert.ToDecimal(m.Groups["total"].Value));
Assert.AreEqual(0.75, Convert.ToDecimal(m.Groups["sub"].Value));

Now the regex matches the string and Success is true.
the ["total"] comes out to 19, but the ["sub"] is 0 instead of 0.75

Can someone give me an idea how to make the decimal part optional, but also have it pick it up in the group.
I have been having trouble matching the numbers, I dont know yet if I may have to squeeze a comma in there oO

Man Bear Pig
Try this:

String line1 = "Total $19 | Subtotal $0.75";
String pattern = "@^\w+\s\$(?<Total>\d+)\s\|\s\w+\s\$(?<Sum>[\d\.]*)$";
Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = regex.Match(line1);
if (m.Success)
{
....do your stuff
}
John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
  • Marked As Answer byMan Bear Pig Saturday, September 19, 2009 5:42 PM
  •  
JohnGrove
Or if you prefer your pattern, make this change:

Total \$(?<total>\d+(?:\.\d{2})?) \| Subtotal \$(?<sub>\d*\.?\d{2}?)
John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
  • Marked As Answer byMan Bear Pig Saturday, September 19, 2009 5:42 PM
  •  
JohnGrove
Try this:

String line1 = "Total $19 | Subtotal $0.75";
String pattern = "@^\w+\s\$(?<Total>\d+)\s\|\s\w+\s\$(?<Sum>[\d\.]*)$";
Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = regex.Match(line1);
if (m.Success)
{
....do your stuff
}
John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
  • Marked As Answer byMan Bear Pig Saturday, September 19, 2009 5:42 PM
  •  
JohnGrove
Or if you prefer your pattern, make this change:

Total \$(?<total>\d+(?:\.\d{2})?) \| Subtotal \$(?<sub>\d*\.?\d{2}?)
John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
  • Marked As Answer byMan Bear Pig Saturday, September 19, 2009 5:42 PM
  •  
JohnGrove

You can use google to search for other answers

Custom Search

More Threads

• store regular expression in app.config
• Replacing href anchor tags with the href value
• Need regex to omit the strings with <followedby> or white spaces
• Simple Regular Expression
• How can I convert this c# code into a regular expression?
• Can this regular expression be simplified?
• Unrecognized escape sequence \*
• regex to fnid a sentence. help!!!
• Need to create a username validation regex
• regex for mobile numbers