正则表达式匹配多个特定括号

时间:2014-02-23 01:13:02

标签: ruby regex

拿字符串:
"The only true (wisdom) is in knowing you know (nothing)"
我想提取nothing

我对此了解:

  • 它将始终位于括号内
  • 括号将始终是行尾之前的最后一个元素:$

我首先尝试将其与之匹配 /\(.*\)$/,但显然已经归来了 (wisdom) is in knowing you know (nothing)

6 个答案:

答案 0 :(得分:4)

您希望使用负字符组匹配,例如[^...]

s = 'The only true (wisdom) is in knowing you know (nothing)'
s.match(/\(([^)]+)\)$/).captures

Regular expression visualization

Debuggex Demo

在这种情况下,nothing位于第一个子组匹配中,但整个正则表达式在技术上与(nothing)匹配。要与{em>整个匹配完全匹配nothing,请使用:

s = 'The only true (wisdom) is in knowing you know (nothing)'
s.match(/(?<=\()([^)]+)(?=\)$)/).captures

Regular expression visualization

Debuggex Demo

答案 1 :(得分:1)

我愿意

s = 'The only true (wisdom) is in knowing you know (nothing)'
s.match(/\(([^)]+)\)$/).captures # => ["nothing"]

答案 2 :(得分:0)

您可以使用scan查找所有匹配项,然后选择最后一项:

str = "The only true (wisdom) is in knowing you know (nothing)"
str.scan(/\((.+?)\)/).last
#=> "nothing"

答案 3 :(得分:0)

您可以使用匹配字符串结尾的 \ z 。试试

  

\([A-Z] + \)\Ž

方式更简单,除了你需要的东西之外别无其他。

在此测试:

http://rubular.com/

答案 4 :(得分:0)

如果有任何嵌套机会,那就更难了。在这种情况下,您需要一些递归:

"...knowing you know ((almost) nothing)"[/\(((?:[^()]*|\(\g<1>\))*)\)$/, 1]
#=> "(almost) nothing"

答案 5 :(得分:0)

看看马,没有正则表达式!

s = 'The only true (wisdom) is in knowing you know (nothing)'

r = s.reverse
r[(r.index(')') + 1)...(r.index('('))].reverse
  #=> "nothing"