How would I match regex with a String of unknown length, but in a specific pattern?

Viewed 157

I'm having trouble figuring out what's wrong with my regex for a string that can be any length but always follows the pattern below

"(A,B)" = valid
"(A,B) (B,C)" = valid

Basically, parenthesis "(", A-Z letter, comma, A-Z letter, parenthesis ")", a white space if and only if there the sequence begins again, otherwise no whitespace.

So far I've gotten to "^\\([A-Z]?,[A-Z]?\\)*.\\([A-Z]?,[A-Z]?\\).*$" but I'm not sure what about my regex is not working right.

2 Answers

You can use the regex,

^(?:\s?\([A-Z],[A-Z]\)(?:\s\([A-Z],[A-Z]\))?)*$

Demo

Description:

  • ^: Asserts position at start of a line
  • (?:: Start of non-capturing group
    • \s?: Optional whitespace character
    • \(: The character (
    • [A-Z]: The character, A to Z
    • ,: The character ,
    • [A-Z]: The character, A to Z
    • \): The character (
    • (?:: Start of non-capturing group
      • \s\([A-Z],[A-Z]\): Pattern already explained above
    • ): End of non-capturing group
    • ?: Makes the last non-capturing group optional
  • ): End of non-capturing group
  • *: Matches the previous token between zero and unlimited times
  • $: Asserts position at the end of a line

A better solution (courtesy: The fourth bird):

You can also optionally repeat n groups after the first match i.e.

^\([A-Z],[A-Z]\)(?: \([A-Z],[A-Z]\))*$

Demo

Try this one..

([(]([A-Z])\,([A-Z])[)])(\s[(]([A-Z])\,([A-Z])[)])*

final String regex = "([(]([A-Z])\\,([A-Z])[)])(\\s[(]([A-Z])\\,([A-Z])[)])*";
Related