Home > Software engineering >  Regex repeating optional group
Regex repeating optional group

Time:03-16

I have an expected expression to be of the form:

A_B_C_D

Sometimes, A can be many parts, such as:

a_b
a-b
a_b_c
a-b-c

etc. to a max of 6 items.

I have gotten to the below regex, but can't seem to get the correct one (not grouping constituents correctly for A).

([[:alnum:]] )[-_]{0,6}([[:alnum:]] ){0,6}[-_]([[:alnum:]] )[-_]([[:alnum:]] )[-_]([[:alnum:]] )

Is there a regex that can do this?

EDIT

Addng some examples:

  1. A_B_C_D
    G1 - A
    G2 - B
    G3 - C
    G4 - D

  2. a-b_B_C_D
    G1 - a-b
    G2 - B
    G3 - C
    G4 - D

  3. a_b_c_B_C_D
    G1 - a_b_c
    G2 - B
    G3 - C
    G4 - D

CodePudding user response:

It seems what could work would be:

^([[:alnum:]] (?:[_-][[:alnum:]] ){0,5})_([[:alnum:]] )_([[:alnum:]] )_([[:alnum:]] )$

See this online demo.


  • ^ - Start-line anchor;
  • ([[:alnum:]] (?:[_-][[:alnum:]] ){0,5}) - 1st Capture group 'A' to hold 1 alnum-chars with an non-capturing group to allow for both delimiters and 0-5 optional parts;
  • _([[:alnum:]] ) - This parts repeats 3 times in the pattern to make up/force group 'B', 'C' and 'D';
  • $ - End-line anchor.
  • Related