Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在使用 Ruby 2.0。我目前有一串:
str = "bar [baz] foo [with] another [one]" str.scan(/\[.*\]/)
输出是:
["[baz] foo [with] another [one]"]
当我期望它更像:
["[baz]","[with]","[one]"]
所以我基本上需要将“[]”之间的所有内容放入一个数组中。有人可以告诉我我错过了什么吗?
你.*是贪婪的,所以它直到最后一个括号才会停止。
.*
您需要使用惰性量词.*?或仅捕获非括号:[^\]]*
.*?
[^\]]*
默认情况下,正则表达式是贪婪的,因此您的正则表达式会抓取从第一个 [ 到最后一个 ] 的所有内容。让它像这样不贪婪:
str.scan(/\[.*?\]/)