Reputation: 7128
In .NET, I'm trying to parse strings like these into groups of numbers. The "a" and "b" are optional (but fixed) letters:
111a222b333 --> groups: num1=111, num2=222, num3=333
111 --> groups: num1=111
111b333 --> groups: num1=111, num3=333
b333 --> groups: num3=333
The regular expressions I've tried include:
(?<num1>\d+)?a?(?<num2>\d+)?b?(?<num3>\d+)?
(?<num1>\d+)*.*(a(?<num2>\d+))*.*(b(?<num3>\d+))*
But they are not working. Any suggestions?
Upvotes: 0
Views: 63
Reputation: 26157
You need combine the ?
(zero or one of) so to speak in a group (not a capture group).
Thus turning this:
a?(?<num2>\d+)
Into:
(?:a(?<num2>\d+))?
The full regex would then be:
(?<num1>\d+)?(?:a(?<num2>\d+))?(?:b(?<num3>\d+))?
Here's a live preview.
As you can see it correctly yields:
Upvotes: 2
Reputation: 68667
(?<num1>\d*)?a?(?<num2>\d*)?b?(?<num3>\d*)
You were close, just needed to cover the case when the digit isn't there.
Upvotes: 1
Reputation: 1
This is a similar post: Regular expression to match any character being repeated more than 10 times
/([0-9])\1*/
should match what you're looking for, since in .NET, quantifiers are greedy by default.
Upvotes: -1