当匹配应该从字符串的末尾完成时,我对在 Ruby 中使用非贪婪的正则表达式感到困惑。
假设我的字符串:
s = "Some words (some nonsense) and more words (target group)"
Run Code Online (Sandbox Code Playgroud)
我想得到“(目标群体)”的结果。我怎样才能做到这一点?正在尝试以下操作:
贪婪的:
s.match(/\(.*\)$/)[0]
=> "(some nonsense) and more words (target group)"
s.match(/\(.*\)/)[0]
=> "(some nonsense) and more words (target group)"
Run Code Online (Sandbox Code Playgroud)
非贪婪:
s.match(/\(.*?\)/)[0]
=> "(some nonsense)"
s.match(/\(.*?\)$/)[0]
=> "(some nonsense) and more words (target group)"
Run Code Online (Sandbox Code Playgroud)
请注意,初始字符串在“()”中可能包含也可能不包含任意数量的组。
非贪婪的正则表达式方法使用 scan
s.scan(/\(.*?\)/).last
=>"(target group)"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4618 次 |
| 最近记录: |