1

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?

0

3 Answers 3

3

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}?)$");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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 -.

1 Comment

Thanks stema. Let me give this a go as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.