Might be a duplicate; I thought this question had to have been already asked, but I searched and couldn’t find one.
How do you determine, using RegExp, whether or not a substring is between parentheses?
Say I want to check if the text “fox” is surrounded by parentheses in the following sentence:
The (quick) brown fox jumps (over) the lazy dog.
I tried this RegEx, but it tests true when “fox” is actually not parenthesized but does have parentheses to its left and right:
\(.*?fox.*?\)
I tried it with negative lookbehind and negative lookahead, and it doesn’t work either:
\(.*?(?<!\)).*?fox.*?(?!\().*?\)
CodePudding user response:
Here's a way to guaranteed that the word exists in inner parentheses only without existing in something nested:
https://regex101.com/r/UlQpM6/1
\([^()]*fox[^()]*\)
\(
- Open
[^()]*
- 0 or more of any character that isn't parentheses
fox
- fox
[^()]*
- repeat pattern
\)
- Close
CodePudding user response:
This will match any term in parenthesis:
\(.*?\)
The (quick) brown fox jumps (over) the lazy dog.
This question mark will ensure that the regex is 'lazy' and will only match the first instance of a closing parenthesis.
Removing the question mark like this: \(.*\)
will give you the following match, which is probably not what you want:
The (quick) brown fox jumps (over) the lazy dog.
If you literally only want to match "(fox)", then the correct regex is:
\(fox\)
You can use an online regex tester or text editor to answer these kind of questions.