Dan Prince
Dan Prince

Reputation: 30009

Regex match parenthesis that are not within square braces

I'm trying to determine with an expression contains parentheses (...), where the (...) are not within a square braces. This is for use with parsing and processing some simple lisp style expressions.

I've adapted the following working expression that I used to split a string on space characters that are not within square brackets, but I can't seem to achieve the same effect for the above case.

The expression I am using:

/(\[.*?\]|(\(.*\)+))/g

Here are a list of example expressions with their desired output from a hasPair function.

 - (+ 2 2) -> true
 - (+ 2 (- 4 2)) -> true
 - [(+ 2 2)] -> false 
 - [(def i (+ 2 2)] -> false
 - (defn add [+ 2 2]) -> true
 - def add [(+ 2 2)] -> false
 - (defn add x y [(+ x y]) -> true

I'm probably missing something obvious, but I can't see what it is.

(The expressions will always be balanced, if that makes a difference)

Upvotes: 3

Views: 2059

Answers (4)

anubhava
anubhava

Reputation: 786291

I would suggest keeping things simple here. Consider code below:

/\([^)]*\)/.test(str.replace(/\[[^\]]*\]/g, ''));

Which solves this task in 2 steps:

  1. First phase: replace all [...] matches by empty string "".
  2. Second phase: Check whether (...) is still present in the replaced string.

Working Demo: http://ideone.com/aVu9iR

Upvotes: 0

Martin Jespersen
Martin Jespersen

Reputation: 26193

Regexes is but one of many tools, and best suited for certain tasks - this is not one of them.

If the pairs are always balanced, all you really need is to know weather or not a left square bracket precedes a left parentheses in any given string.

This is quite easily achieved by evaluating the following

str.indexOf('[') < str.indexOf('(')

Upvotes: 1

progrenhard
progrenhard

Reputation: 2363

(?:[^[]|^)\(([\w]*)\)(?!\])

Regular expression visualization

Edit live on Debuggex

Not really sure what you are looking for but this is what it looks like!

new edit:

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

Regular expression visualization

Edit live on Debuggex

edit 3:

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

Regular expression visualization

Edit live on Debuggex

Upvotes: 1

Jerry
Jerry

Reputation: 71598

Maybe you could try this one:

\([^\)]+\)(?![^\[]*\])

regex101 demo

This will work only if the square brackets (and parentheses too I think) are balanced.

EDIT: Okay, it's a crazy regex now xD

\((?:[^\)\[\]]+|(?:[^\[\]\)]*\[[^\[\]\)]*\][^\[\]\)]*))*\)(?![^\[]*\])

regex101 retry

Upvotes: 1

Related Questions