I want to match with one of strings: ab10, cd14, ef23, mn99
Regex: (ab10|cd14|ef23|mn99)
How can I capture words: ab, cd, ef, mn (first 2 characters of group $1)
CodePudding user response:
You can add a (?=(..))
or (?=(.{2}))
lookahead containing another capturing group at the start:
(?=(..))(ab10|cd14|ef23|mn99)
(?=(.{2}))(ab10|cd14|ef23|mn99)
See the regex demo.
The two chars will land in Group 1 and the full found match in Group 2.
Another way to get it is via a branch reset group:
(?|(ab)10|(cd)14|(ef)23|(mn)99)
See this regex demo. The two char combinations will be in Group 1.