【问题标题】:how to check if in parenthesis in regex [duplicate]如何检查正则表达式的括号中是否包含[重复]
【发布时间】:2011-11-13 00:26:53
【问题描述】:

可能重复:
Regex - nested patterns - within outer pattern but exclude inner pattern

我正在尝试在单词之后/从单词中获取字符串的子字符串。但我希望这个词在括号之外。例如:

something (theword other things) theword some more stuff 应该给我theword some more stuff 而不是theword other things) theword more stuff。我怎样才能在正则表达式中做到这一点。我正在使用 PCRE(例如 php、python 正则表达式引擎)

编辑:

我试图使用这个正则表达式的字符串是一个 mysql 语句。我正在尝试删除部分直到 FROM 部分,但内部 sql 语句(括号中的语句给我带来了问题)。

【问题讨论】:

  • foo\(bar\)baz 算作括号还是仅算作foo(bar)baz
  • 我确定我的括号不会被转义。

标签: regex


【解决方案1】:

这是一项类似于此问题中描述的任务:Regex - nested patterns - within outer pattern but exclude inner pattern

请参阅我的答案,了解为什么它不是 100% 可能,以及大多数情况下都有效的 hack-ish 解决方案(即对于浅嵌套)。

更新:

如果您知道括号既不会嵌套也不会转义,您可以使用类似的东西:

(?<=\)|^)([^()]+)(?=\(|$)

所以用这个作为大海捞针:

something (theword other things) theword (some) more stuff

你最终会在捕获组 1 中使用这些 sn-ps:

something 
 theword 
 more stuff

请注意,还捕获了前导/尾随空格,以防止它们使用它来代替:

(?<=\)|^)\s*([^()]+)\s*(?=\(|$)

相同的正则表达式模式,但使用 cmets:

(?<=\)|^) #either ")" or beginning of string
\s* #optional leading whitespace
([^()]+) #any sequence of characters but "(" or ")"
\s* #optional trailing whitespace
(?=\(|$) #either "(" or end of string

【讨论】:

  • 我确信我的模式不会使用嵌套括号。我已经编辑了我的第一篇文章。
  • 嵌套括号不是问题。你只是做错了。
  • @tchrist:希望看到更好的解决方案,介意发布一个吗?
  • pcrepattern 手册页中匹配嵌套括号的标准模式是 ( \( ( [^()]++ | (?1) )* \) ),尽管我倾向于使用 perlre 手册页中的 ( \( (?: [^()]++ | (?-1) )*+ \) ) ( v5.10 或更高版本)在相对组 -1 而不是绝对组 1 上递归,这样我就不必重新编号。更好的是,通过(?&lt;paren&gt; \( (?: [^()]++ | (?&amp;paren) )*+ \) ) 使用命名组paren,忘记编号组。这些都在/x模式ᴀᴋᴀ"(?x)"PCRE_EXTENDED,因为ihatereadingstuffruntgetherlikethis。
猜你喜欢
  • 1970-01-01
  • 2012-09-13
  • 2018-08-09
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
相关资源
最近更新 更多