Search code examples
javascriptregexstringbracketsparentheses

How do you determine, using RegExp, whether or not a substring is between parentheses?


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.*?(?!\().*?\)

Solution

  • 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