Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c# - .NET regex matching digits between optional text with possessive quantifer is not working

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

*+ 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...