1

Consider following text:

aas(  I)f df (as)(dfdsf)(adf).dgdf(sfg).(dfdf) asdfsdf dsfa(asd #54 54 !fa.) sdf

I want to retrive text between parenthesis, but adjacent parentheses should be consider a single unit. How can I do that?

For above example desired output is:

  • ( I)
  • (as)(dfdsf)(adf)
  • (sfg).(dfdf)
  • (asd #54 54 !fa.)
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173

4 Answers4

1

try [^(](\([^()]+([)](^[[:alnum:]]*)?[(][^()]+)*\))[^)]. capture group 1 is what you want.

this expression assumes that every kind of character apart from parentheses mayy occur in the text between parentheses and it won't match portions with nested parentheses.

collapsar
  • 17,010
  • 4
  • 35
  • 61
1

I'd go with: /(?:\(\w+\)(?:\.(?=\())?)+/g

  • \(\w+\) to match a-zA-Z0-9_ inside literal braces
  • (?:\.(?=\())? to capture a literal . only if it's followed by another opening brace
  • The whole thing wrapped in (?:)+ to join adjacent captures together
var str = "aas(I)f df (asdfdsf)(adf).dgdf(sfg).(dfdf) asdfsdf dsfa(asdfa) sdf";
str.match(/(?:\(\w+\)(?:\.(?=\())?)+/g);
// -> ["(I)", "(asdfdsf)(adf)", "(sfg).(dfdf)", "(asdfa)"]
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • Just noticed that your question was for [tag:php]. Shows how much attention I paid, but the regex will still work! – Andy E Mar 15 '13 at 14:17
1

Assumption

  • No nesting (), and no escaping of ()
  • Parentheses are chained together with the . character, or by being right next to each other (no flexible spacing allowed).
  • (a)(b).(c) is consider a single token (the . is optional).

Solution

The regex below is to be used with global matching (match all) function.

\([^)]*\)(?:\.?\([^)]*\))*

Please add the delimiter on your own.

DEMO

Explanation

Break down of the regex (spacing is insignificant). After and including # are comments and not part of the regex.

\(             # Literal (
[^)]*          # Match 0 or more characters that are not )
\)             # Literal ). These first 3 lines match an instance of wrapped text
(?:            # Non-capturing group
  \.?          # Optional literal .
  \([^)]*\)    # Match another instance of wrapped text
)*             # The whole group is repeated 0 or more times
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
-2

This one should do the trick:

\([A-Za-z0-9]+\)
Borniet
  • 3,544
  • 4
  • 24
  • 33