0

I have this string:

String str = "Displaying bills 1 - 20 of 10000 in total";

And i want to parse the total value, 10000 in this case. This is what i have try:

Regex regex = new Regex(@"\\d+(?=\\s*in total)");
Match match = regex.Match("Displaying bills 1 - 20 of 10000 in total");
if (match.Success)
{
    Console.WriteLine(match.Value);
} 

And currently this now succeed.

Dana Yeger
  • 617
  • 3
  • 9
  • 26
  • Don't delimit backslashes in verbatim strings. So use `@"\d+(?=\s*in total)"` or `"\\d+(?=\\s*in total)"` (no `@`). – juharr Sep 02 '16 at 11:44
  • Yeah, the `@"\"` means 1 literal backslash and you have 2 before `d`, matching a ``\`` and a `d` in the text. When you remove `@` and make the string literal a regular one, the `"\\"` will get parsed exactly as 1 literal backslash that is necessary for the regex engine to parse `\d` as a digit shorthand character class. – Wiktor Stribiżew Sep 02 '16 at 12:04

2 Answers2

-1

As mentioned in comment by @juharr, you just need to remove the double backslashes. The @ at the beginning of the string marks it as a verbatim string, which doesn't require special characters to be escaped.

js441
  • 1,134
  • 8
  • 16
  • The only issue is the delimited backslashes since the OP only wants to match the number before "in total". Your's will match the entire string instead. – juharr Sep 02 '16 at 11:58
  • You're correct. For some reason I thought he was getting the value from match.groups[1], which required the digits to be grouped. I'll edit. – js441 Sep 02 '16 at 12:04
-1
        string text = "Displaying bills 1 - 20 of 10000 in total";
        Regex r = new Regex(Regex.Escape("of") +"(.*?)"+Regex.Escape("in"));
        MatchCollection matches = r.Matches(text);
        MessageBox.Show(matches[0].Groups[1].Value);
FreeMan
  • 1,417
  • 14
  • 20
  • 1
    Why are you escaping string literals that don't contain anything that needs to be escaped in the first place? – juharr Sep 02 '16 at 12:05