Alexander
Alexander

Reputation: 55

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)?

Upvotes: 0

Views: 142

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

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.

Upvotes: 1

Poul Bak
Poul Bak

Reputation: 10940

You can use the following regex:

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

Basically it injects a Group looking for 'oops' then it doubles the '[\w\W]*?' matching both before and after the captured Group.

Now 'oops' will be in Group 2.

Upvotes: 0

Related Questions