1

I am trying to write a regular expression to match any string that satisfies the following criteria.

The string begins and ends with a matching pair of parentheses '(' ')'

There may be any number of parentheses within it.

For example my regex shud match :

( ( p(x)+q(x) ) . (p(x) * q(x) ) )

but not match

( p(x)+q(x) ) . ( p(x) * q(x) )

How do i write such a regex

AnkurVj
  • 7,258
  • 9
  • 40
  • 52
  • Are you trying to say that all the internal parenthesis must match as well? If that is the case, I believe you would need to use a Push-Down-Automata instead of a regular expression to solve that, as a Finite-State-Automata (which define the space for a regex) does not allow for that type of a check. – aperkins Sep 13 '10 at 16:11
  • To clarify my comment - if you are looking for a regex to solve a[n]b[n], where you have an equal number of a – aperkins Sep 13 '10 at 16:11
  • dangit - stupid enter key - continuing: an equal number of a's and b's, then you would not be able to solve that general case with a regular expression. Based on what you have described, it seems like that is what you are looking for (in a variation, of course) which would require a PDA. – aperkins Sep 13 '10 at 16:12
  • To clarify, i am assuming that in my input all parentheses match. The only issue is that i want to capture those strings where the very first '(' matches the last ')'. That is, something like ( ... ) – AnkurVj Sep 13 '10 at 16:21
  • Now if i write a regex like ^\\(.*\\)$ _JavaStyle_ then i match also the strings of the form (..)(..) and not just ( .... ) – AnkurVj Sep 13 '10 at 16:23
  • That is my point - if all of the parenthesis must match, then you have a situation where you want to prove that there are equal, matching elements of two characters - which is the equivalent of the a and b example I give earlier. – aperkins Sep 13 '10 at 16:57

2 Answers2

2

Please do a better search next time: http://www.google.com/search?q=site%3Astackoverflow.com+regex+match+parentheses&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Here's your answer: Regular Expression to match outer brackets

Community
  • 1
  • 1
Rodney Gitzel
  • 2,542
  • 15
  • 21
  • Yep, as the accepted answer notes - this is a simple algorithmic problem, not really appropriate for regex. Thanks for the link. – aperkins Sep 13 '10 at 16:55
1

Doing any sort of parsing like this using regular expressions is difficult and almost always a bad idea. See this answer to this question. Oh, the horror!

Community
  • 1
  • 1
Kelly S. French
  • 11,669
  • 9
  • 56
  • 90