HattrickNZ
HattrickNZ

Reputation: 4643

regex + capturing groups with varying conditions

working on the regex here https://regex101.com/r/wI2cG1/1

this is the data:

K'1234567
K'123456789
K'123456

I am interested in the digits after K'
I am looking to do this using regex but not sure if it can be done. What I want is:
if the number has 6 digits return the first 2 digits e.g. 12
if the number has 7 digits return the first 3 digits e.g. 123
if the number has 9 digits return the first 4 digits e.g. 1234

also if the number has 10 or 11 digits return the first 3 digits e.g. 123

and I want to return these to different capturing group names or if possible the same capturing group name.

Upvotes: 2

Views: 49

Answers (1)

hwnd
hwnd

Reputation: 70722

It's possible to maintain the results in one group using the branch reset feature:

K'(?|(\d{2,3})\d{4}|(\d{4})\d{5}|(\d{3})\d{7,8})\b

Regex Demo

Upvotes: 3

Related Questions