1

I am having an issue with identifying a multiple character digit in a string.

What I am attempting to do is check, from right to left, for the first digits for comparison.

My original regex:

Regex.Match(s, @"\d{3}", RegexOptions.RightToLeft);

This would match the first 3 digits it came across in any string. Eg:

  • hello123 - Output: 123
  • good234bye - Output: 234
  • see-you-456-tomorrow - Output: 456

No worries. However, now we're not certain of the length the number might be, so we have changed the Regex to this:

Regex.Match(s, @"\d*", RegexOptions.RightToLeft);

This looks for the first string of digits, any length, and uses that. However, it returns an empty match if the number is not on the end of the string. Eg:

  • hello12 - Output: 12
  • good-bye-1234 - Output: 1234
  • see-1-you-2-morrow - Output: Nothing

How can I look for the first x-length of digits in a string, from right to left and disregarding any non-digit characters, without it returning an empty match?

Ben
  • 2,433
  • 5
  • 39
  • 69

2 Answers2

0

Can you try this? I'm new to Regex, but I guess it works for you!

 var s =    @"see-you-456-tomorrow";
            var r = Regex.Match(s, @"[[\d]]*\d*", RegexOptions.RightToLeft);
            Console.WriteLine(r);

You can see it working here.

Arthur Castro
  • 610
  • 6
  • 18
  • That regex means: `[[\d]` a digit or a "[" **+** `]*` a "]" repeated once or more times **+** `\d*` a digit once or more times. Test against the string "`see-you-456-tomorrow[`" to see the difference – Mariano Sep 22 '15 at 01:36
  • The result will be 456, the first match (right to left). What you want the result to be Ben & @Mariano? – Arthur Castro Sep 22 '15 at 01:37
  • @ArthurCastro That's the expected result, yes. Nice job on the first try! – Ben Sep 22 '15 at 01:48
0

Quantifiers

A digit repeated once or more times

\d+

A digit repeated from 3 times to 5 times

\d{3,5}

A digit repeated at least 5 times

\d{5,}

You can read more about quantifiers in this tutorial


As you may have realized,

              see-1-you-2-morrow
                                ^
                                |
\d* matches an empty position (here)
    between the last character and the end of string
Mariano
  • 6,423
  • 4
  • 31
  • 47