tags:

views:

78

answers:

2

Hi

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

+2  A: 

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: http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets

Rodney Gitzel
Thanx for the pointer
AnkurVj
Yep, as the accepted answer notes - this is a simple algorithmic problem, not really appropriate for regex. Thanks for the link.
aperkins
+1  A: 

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!

Kelly French
lol nicely put by the author
AnkurVj