-1

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!

user3995789
  • 3,452
  • 1
  • 19
  • 35

1 Answers1

0

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • what's the difference between [non-capturing group](http://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group) and square brackets? – user3995789 May 21 '16 at 10:29