3

I want a string, which must be in parentheses () and separated with a comma , something like: (aaa),(bbbb),(cccccccc)

How could I match that using regular expression?

blue
  • 2,683
  • 19
  • 29
zeder127
  • 69
  • 1
  • 3
  • 5

3 Answers3

6

You can try this

^(?!,)(,?\(\w+\))+$

^ marks the beginning of string

$ marks the end of string

Both ^,$ are required else it would match in between

\w+ matches 1 to many of [a-zA-Z\d_]

,? would optionally match ,

^(?!,) would look for , at the beginning of string and if it finds it,it doesn't match further.If it doesn't find,it returns to the previous position i.e at the start of string

Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

This regex

\(([^\)])\)

will match everything that's inside parethenses. You can use it to find submatches or whatever you need.

I suggest you first tokenize, saving in different variables what's separated by commas, and then use the regular expression to match what's inside the parentheses.

blue
  • 2,683
  • 19
  • 29
0

This should do it:

/^\(([^)])\1*\)(?:,\(([^)])\2*\))*$/

using backreferences for the repeated characters, escaped parenthesis around them, and allowing it to be followed by the same thing many times - delimited with commata. Altogether anchored on the whole string.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375