简体   繁体   中英

Regular expression Match for numeric pattern

I am working on parsing the user provided input for a number which belongs to a specified pattern such as 199-234

where the

  1. first component is 1
  2. second component is 99
  3. third component is 234

The user would provide just the first few digits or the entire string. I intend to parse each of the components out. The reg-ex that I have come up with is -

Regex regex = new Regex(@"(?<first>\d)(?<second>\d{0,2})-?(?<third>\d{0,3})");
var groups = regex.Match(input);

If I provide the input 199 , the reg-ex pattern breaks them into 3 groups instead of the expected 2. Actual result is

  1. first component is 1
  2. second component is 9
  3. third component is 9

How do I ensure that the inputs get correctly matched in this case?

Try the non-greedy version of the third group: \\d{0,3}?

Regex regex = new Regex(@"(?<first>\d)(?<second>\d{0,2})-?(?<third>\d{0,3}?)");
var groups = regex.Match(input);

It also might help (for clarity's sake) to bind the beginning and end of the strings ( ^ and $ )

new Regex(@"^(?<first>\d)(?<second>\d{0,2})-?(?<third>\d{0,3}?)$");

Because your expression requires a third element it cannot match 199 as only two groups because it needs three groups for a match.

Also you are allowsing matches of zero length for your second and third groups.

Try requireing exactly two characters for the second group or making the third group optional.

Make the complete last part optional and not only the -

@"(?<first>\d)(?<second>\d{0,2})(?:-(?<third>\d{0,3}))?"

I put the complete last part starting with the - into an optional non-capturing ( (?:) ) group (?:-(?<third>\\d{0,3}))? . So it will search only for the third group if there is a - .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM