Make a regex that matches this:
aaGrest
with matching groups [aa, G, rest]
bb
with matching groups [bb]
I am trying to make Grest
part optional this doesn't work:
^([a-z]{2}[a-z]?)[(P|G)(.*)]?
Ps: dont complicate stuff or downvote!
Make a regex that matches this:
aaGrest
with matching groups [aa, G, rest]
bb
with matching groups [bb]
I am trying to make Grest
part optional this doesn't work:
^([a-z]{2}[a-z]?)[(P|G)(.*)]?
Ps: dont complicate stuff or downvote!
Try this:
^([a-z]{2}[a-z]?)(?:(P|G)(.*))?
See live demo.
This uses a non-capturing group (syntax (?:...)
) to group the optional part without forming a capturing group, which keeps the capturing groups numbered as 1, 2 and 3.
Square brackets form a character class, which isn't what you intended.