2

I have this regex:

Regex myRegex = new Regex(@"^[a-zA-Z .:_-]+([0-9]+)[a-zA-Z .:_-]*+$");

and I would like to match a digit code this way:

  • "Order No. 0123456 lorem ipsum" - MATCH 0123456 in Group 1
  • "No. 0123456" - MATCH 0123456 in Group 1
  • "Order 0123456" - MATCH 0123456 in Group 1
  • "013456 lorem ipsum" - NO MATCH

This works here: https://regex101.com/ but not in .NET with C# as I have this exception:

"System.ArgumentException: parsing "^[a-zA-Z .:_-]+([0-9]+)[a-zA-Z .:_-]*+$" - Nested quantifier +.
   at System.Text.RegularExpressions.RegexParser.ScanRegex()
   at System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op)
   at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, TimeSpan matchTimeout, Boolean useCache)
   at System.Text.RegularExpressions.Regex..ctor(String pattern)
   at Rextester.Program.AnalyzeFreetext(String freeText)
   at Rextester.Program.Main(String[] args)"

Is there an alternative an maybe more elegant way to capture the digits between text (mandatory before digits, optional after).

Thank you.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
refex
  • 173
  • 6
  • 10

2 Answers2

4

*+ is a possessive quantifier, and .NET regex does not support them. Replace *+ with * as you did not mean to use a possessive quantifier here.

Here is the mapping:

?+     => ?
*+     => *
++     => +
{2}+   => {2}
{2,}+  => {2,}
{2,9}+ => {2,9}

Use

^[a-zA-Z .:_-]+([0-9]+)[a-zA-Z .:_-]*$

See the .NET regex demo.

enter image description here

An alternative regex can be used here, that will match Order or No., then 0+ whitespaces and then will capture 1+ digits:

(?:Order|No\.)\s*([0-9]+)

See another regex demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You can use the following Regex which enforces anything else prior the digits then captures the digits:

\D+(\d+)

See the details below.

\D means anything else but digits
+ at least 1 time
\d digits only
+ at least 1 time

Feel free to ask questions in the comments.

StfBln
  • 1,137
  • 6
  • 11