2

当匹配应该从字符串的末尾完成时,我对在 Ruby 中使用非贪婪的正则表达式感到困惑。

假设我的字符串:

s = "Some words (some nonsense) and more words (target group)"

我想得到“(目标群体)”的结果。我怎样才能做到这一点?正在尝试以下操作:

贪婪的:

s.match(/\(.*\)$/)[0]
=> "(some nonsense) and more words (target group)"

s.match(/\(.*\)/)[0]
=> "(some nonsense) and more words (target group)"

非贪婪:

s.match(/\(.*?\)/)[0]
=> "(some nonsense)"

s.match(/\(.*?\)$/)[0]
=> "(some nonsense) and more words (target group)"

请注意,初始字符串可能包含也可能不包含“()”中的任意数量的组。

4

4 回答 4

5

使用非贪婪正则表达式方法scan

s.scan(/\(.*?\)/).last
=>"(target group)"
于 2013-11-15T01:00:16.433 回答
2

不确定我是否理解你的问题。因此,如果我弄错了,我深表歉意:

你确定你需要.*?什么时候[^)]*做?

s.match(/\([^)]*\)$/)[0]
=> "(target group)"

如果您仍然坚持使用.*?,请在不情愿的匹配之前使用贪婪匹配:

s.match(/^.*(\(.*?\))$/)[1]
=> "(target group)"
于 2013-11-15T00:56:27.473 回答
1

这是一个非正则表达式版本:

s = "Some words (some nonsense) and more words (target group)"

p s[(s.rindex('(')+1)...s.rindex(')')] #=> target group
于 2013-11-15T08:15:31.533 回答
0

带有负前瞻的负集

s.match(/\([^)]*\)(?!.*\(.*\))/)[0]

..negative-look-ahead 可以在捕获表达式的末尾

具有负面前瞻性的非贪婪(懒惰)

s.match(/\((?!.*\(.*\)).*?\)/)[0]

.. 负前瞻必须在第一次重复之前(这里懒惰=非贪婪)

于 2016-06-01T10:02:22.333 回答