正则表达式在包含精确子字符串的括号之间查找整个子字符串 [英] Regex find whole substring between parenthesis containing exact substring

查看:43
本文介绍了正则表达式在包含精确子字符串的括号之间查找整个子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有字符串:

"one two  (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)"

我只需要带括号的整个子字符串,包含单词"back",对于这个字符串,它将是:

and I need only whole substring with parenthesis, containing word "back", for this string it will be:

"(87 back sack)"

我试过了:

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

但它返回 "(78-45ack sack); now (87 back sack)"

我的正则表达式应该是什么样的?据我所知,它发生的原因是搜索从字符串的开头开始,通常 - how to perform regex to "search" 从字符串的中间,从单词 "back"?

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

推荐答案

你可以使用这个基于否定字符类的正则表达式:

You can use this regex based on negated character class:

\([^()]*?back[^()]*\)

  • [^()]* 匹配 0 个或多个不是 () 的任何字符,从而确保我们不't 匹配 (...) 对.
    • [^()]* matches 0 or more of any character that is not ( and ), thus making sure we don't match across the pair of (...).
    • RegEx 演示 1

      或者,您也可以使用这个基于负正则表达式的正则表达式:

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

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

      RegEx 演示 2

      • (?!back|[()]) 是否定前瞻,断言当前位置没有 back() 在文本前面.
      • (?:(?!back|\)).)*? 匹配 0 个或多个没有 back() 前面.
      • [^)]* 匹配除 ) 之外的任何内容.
      • (?!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 ).

      这篇关于正则表达式在包含精确子字符串的括号之间查找整个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆