简体   繁体   中英

How to match regex avoid parentheses inside parentheses

I have string expression like this

CONTAIN("A(ASDFASDF)","MAKLOON") &&  !CONTAIN("THIS IS THE (STRING) ","MAKLON") &&  !CONTAIN("ASDFASDF","MAKLUN") &&  ("121"=="" ||  121.00=="" ||  121.0=="")

I want to match only the result like this :

1. CONTAIN("A(ASDFASDF)","MAKLOON") 
2. CONTAIN("THIS IS THE (STRING) ","MAKLON")
3. CONTAIN("ASDFASDF","MAKLUN")

I have try with this regex but the match only this :

CONTAIN\(.*?\)

Result

1. CONTAIN("A(ASDFASDF)
2. CONTAIN("THIS IS THE (STRING)
3. CONTAIN("ASDFASDF","MAKLUN")

How to solve my problem? Thanks

您可以尝试以下模式: CONTAIN\\(.*?"\\)

Here's a slightly enhanced version, which allows the inner string to have parenthesis. It's not perfect either, but probably a bit more secure:

CONTAIN\(".*?", ?".*?"\)

Brief explanation : It matches CONTAIN( , then any character until it finds "," or ", " (optional space, remove ? if you will never have a space there), then again any character until the final ") . The ? after the * is necessary to make it match as little as possible. Otherwise, .* would match as much as possible, from the first to the last CONTAIN string.

Besides matching what you mention in your post, it will also match:

CONTAIN("HEL()LO",")WORLD(")
CONTAIN(")HELLO(",")WORLD(")

And will not match an invalid strings like these, which are matched by the other proposed solutions:

CONTAIN("HELLO",")WORLD()     // partial match
CONTAIN(")
CONTAIN(""")

I tried to do some more complex regex to match the number of quotes or parenthesis, but I think you don't need such complexity, unless your string may have escaped quotes, like \\" or "" .

If you won't get any of those invalid strings or strange strings, you may be good enough with the other simpler regex.

I think the regular expression you're looking for would be: (CONTAIN\\(\\".+\\"\\)) . By including the \\" you get all of the characters inside the quotes instead of ending at the first instance of a ')'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM