Reputation: 30009
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
Reputation: 786291
I would suggest keeping things simple here. Consider code below:
/\([^)]*\)/.test(str.replace(/\[[^\]]*\]/g, ''));
Which solves this task in 2 steps:
[
...]
matches by empty string ""
.(
...)
is still present in the replaced string.Working Demo: http://ideone.com/aVu9iR
Upvotes: 0
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
Reputation: 2363
(?:[^[]|^)\(([\w]*)\)(?!\])
Not really sure what you are looking for but this is what it looks like!
new edit:
(?:[^[]|^)?\((.*)\)(?!\])
edit 3:
(?:[^[]|^)\((.*?)\)(?:(?!\]))
Upvotes: 1
Reputation: 71598
Maybe you could try this one:
\([^\)]+\)(?![^\[]*\])
This will work only if the square brackets (and parentheses too I think) are balanced.
EDIT: Okay, it's a crazy regex now xD
\((?:[^\)\[\]]+|(?:[^\[\]\)]*\[[^\[\]\)]*\][^\[\]\)]*))*\)(?![^\[]*\])
Upvotes: 1