拿字符串:
"The only true (wisdom) is in knowing you know (nothing)"
我想提取nothing
。
我对此了解:
$
我首先尝试将其与之匹配
/\(.*\)$/
,但显然已经归来了
(wisdom) is in knowing you know (nothing)
。
答案 0 :(得分:4)
您希望使用负字符组匹配,例如[^...]
:
s = 'The only true (wisdom) is in knowing you know (nothing)'
s.match(/\(([^)]+)\)$/).captures
在这种情况下,nothing
位于第一个子组匹配中,但整个正则表达式在技术上与(nothing)
匹配。要与{em>整个匹配完全匹配nothing
,请使用:
s = 'The only true (wisdom) is in knowing you know (nothing)'
s.match(/(?<=\()([^)]+)(?=\)$)/).captures
答案 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)
答案 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"