Karthik
Karthik

Reputation: 13

Match a Word which is not followed by a parenthesis for the rest of the string

I have a string like so:

((blah blah AND) (blah AND blah) AND good) AND Zero AND (Blah AND Blah)

I want to match only those "AND's" which are outside any parenthesis, that is only the OUTER AND's

The regex I used was: AND(?!))

And the result was:

I thought of uploading a screenshot of the result here, but SO doesn't allow me to unless

It only doesn't match the AND's where the ')' is immediately followed but it matches the rest of the AND's.

Again, I would ideally want a regex to match only the AND's which occur outside of any parenthesis, that is the outer AND's.

Note that I am implementing this in Java and its regex implementation doesn't support recursive regex. So is the reason that I am attempting this sloppy workaround

I am looking for a better and more robust solution for this.

Upvotes: 1

Views: 79

Answers (1)

Dan31877
Dan31877

Reputation: 26

A Stack would work well here. You can simulate one by setting a variable to count the parenthesis. For left parenthesis +1 and for right -1. If you find an AND and the parenthesis count is 0 then you're all set.

Upvotes: 1

Related Questions