Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match text, but not if contained in brackets [duplicate]

Tags:

regex

I could not find any practical way to do this, myself:

APPLE should be matched

APPLE APPLE should result in two matches

APPLE (APPLE) should result in one match

(BANANA APPLE) should result in no matches

()APPLE() should result in one match

The brackets can be separated from the wanted string by any length of text over multiple lines. Other brackets not containing the string can exist in any configuration.

EDIT None of the answers thus far (and thanks for them!) allow for newline characters between the brackets. Is this not a possibility?

like image 970
Weckar E. Avatar asked Mar 01 '17 08:03

Weckar E.


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Can a regex identify correct bracketing?

Regular expressions can't count brackets.

What does \+ mean in regex?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

Do you need to escape parentheses in regex?

Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash. An explanation of how literalRegex works: / — Opens or begins regex.


1 Answers

Hope this will work fine

Regex: (?<!\()\bAPPLE\b(?![\w\s]*[\)])

\b a word boundary

(?![\w\s]*[\)]) Negatively lookahead for ) followed by words or spaces

(?<!\() Negatively lookbehind for (

RegexDemo

like image 129
Sahil Gulati Avatar answered Oct 24 '22 23:10

Sahil Gulati