Complex regex

I am trying to find a regex that will do the following (works in Javascript). I want to take a string containing some type markers (token)inside parentheses. My goal is to capture tokens (including parentheses). I assume that parenthese are not nested and that every open parenthesis is ultimately closed.

The regular expression that I would use

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

Let me break it:

[            # Either of two things:
  [^\(\)]*   # the first is a substring not containing parentheses
|
  (          # the second is to be captured...
    \(.*?\)  # and should contain anything in parentheses - lazy match
  )
]*           # Any number of these blocks can appear

Needless to say, this will not work (why am I asking here differently?):

var a = /[[^\(\)]*|(\(.*?\))]*/;
a.exec('foo(bar)');

This does not work in both Firefox and Node. My previous attempt was a bit more complex regex:

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

which can be described as follows

(?:              # A non-capturing group...
  [^\(\)]*       # ...containing any number of non-parentheses chars
  (\(.*?\))      # ...followed by a captured token inside parentheses.
)*               # There can be any number of such groups
[^\(\)]*         # Finally, any number of non-parentheses, as above

This will work on foo(bar), but will not work on foo(bar)(quux), if there is only quux.

?

+3
4

. /g : s.match(/\([^\)]+\)/g)

+4

Chrome

<your string here>.match(/(\(.*?\))/g)

:

str = 'Content(cap)(cap2)(cap3)'
str.match(/(\(.*?\))/g)
-> ["(cap)", "(cap2)", "(cap3)"]
+2

If your goal is to capture markers inside brackets (including delimiters), then a simple regular expression, for example:

\([^)]*?\)

will work.

+1
source

var a= /\([^)]+\)/g;

+1
source

All Articles