Search code examples
regexpcre

how to capture group within capture group?


for example, string:

bla bla bla (bla oops bla
bla bla bla 
bla bla bla) bla oops
bla bla bla 
oops bla (bla bla oops
bla)

how i can get 'oops' between brackets? first, i get text between brackets:

(?<=\()([\w\W]*?)(?=\))

can i in the same regex capture group within capture group (find 'oops' within capture group)?


Solution

  • You may use

    (?:\G(?!\A)|\()[^()]*?\Koops
    

    Or, if you must check for the closing parentheses, add a lookahead at the end:

    (?:\G(?!\A)|\()[^()]*?\Koops(?=[^()]*\))
    

    See the regex demo.

    Details

    • (?:\G(?!\A)|\() - ( or end of the previous match (\G(?!\A))
    • [^()]*? - any 0+ chars other than ( and )
    • \K - match reset operator
    • oops - the word you need (wrap with \b if you need a whole word match)
    • (?=[^()]*\)) - a positive lookahead that requires 0+ chars other than ( and ) up to the first ) to appear immediately to the right of the current location.