regexag

Regex for optional parts of string


How can I match all four variants shown below with one regular expression?

ABC
ABC_DEF
ABC_DEF_GHI
ABC_DEF_GHI_JKL

ABC, DEF, GHI, JKL do not represent number of characters.

I've tried something like this (only for second option) but no luck: [A-Z]+(_[A-Z]?+)


Solution

  • here: ^([A-Za-z]+)(_[A-Za-z]+)*$