Reputation: 1005
Lets say I have the following 2 strings:
'506' '1008'
I want to extract the 5 and the 06 from the string and 10 and 08 from the second. I came up with the following regex:
(\d{1,2})(\d{1,2})
This matches 50 and 6 and 10 and 08. This is not completely what I want. I need to match 5 and 06 instead of 50 and 6. How do I indicate I want the second group to receive the higher length?
Upvotes: 1
Views: 145
Reputation: 626845
You may wrap the pattern with word boundaries and capture exactly 2 digits into Group 2:
\b(\d{1,2})(\d{2})\b
See the regex demo
\b
- intial word boundary(\d{1,2})
- Group 1 capturing one or two digits(\d{2})
- Group 2 matching exactly 2 digits\b
- trailing word boundary.Upvotes: 1