当匹配应该从字符串的末尾完成时,我对在 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)"
请注意,初始字符串可能包含也可能不包含“()”中的任意数量的组。