Skip to content Skip to sidebar Skip to footer

Regex Find Whole Substring Between Parenthesis Containing Exact Substring

For example I have string: 'one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)' and I need only whole substring with parenthesis, containing word 'back', for t

Solution 1:

You can use this regex based on negated character class:

\([^()]*?back[^()]*\)
  • [^()]* matches 0 or more of any character that is not ( and ), thus making sure we don't match across the pair of (...).

RegEx Demo 1


Alternatively, you can also use this regex based on negative regex:

\((?:(?!back|[()]).)*?back[^)]*\)

RegEx Demo 2

  • (?!back|[()]) is negative lookahead that asserts that current position doesn't have back or ( or ) ahead in the text.
  • (?:(?!back|\)).)*? matches 0 or more of any character that doesn't have back or ( or ) ahead.
  • [^)]* matches anything but ).

Solution 2:

h="one two  (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)"
l=h.split("(")
[x.split(")")[0] for x in l if ")" in x and "back" in x]

Solution 3:

Try the below pattern for reluctant matching

pattern="\(.*?\)"

Post a Comment for "Regex Find Whole Substring Between Parenthesis Containing Exact Substring"