Regex find whole substring between parenthesis containing exact substring

匆匆过客 提交于 2019-12-24 11:26:48

问题


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 this string it will be:

"(87 back sack)"

I've tried:

(\(.*?back.*?\))

but it's return "(78-45ack sack); now (87 back sack)"

How should my regex look like? As I understood it's happening cause search going from begin of the string, in common - how to perform regex to "search" from the middle of string, from the word "back"?


回答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 ).



回答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]



回答3:


Try the below pattern for reluctant matching

pattern="\(.*?\)"



来源:https://stackoverflow.com/questions/39558667/regex-find-whole-substring-between-parenthesis-containing-exact-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!