【发布时间】:2016-05-04 10:44:01
【问题描述】:
Unix grep 有一个简单的-o, --only-matching 选项,仅显示匹配 PATTERN 的匹配行部分。
使用 grep 方法或任何其他标准方法(不带 exec 或 gems)在 Ruby 中模仿该行为的最简单方法是什么?
给出的例子:
File.open('test.css','r') do |file|
file.each_line do |line|
match=/p[A-Z]+/.match(line)
puts match.to_s unless match.nil?
end
end
会模仿grep -oE "p[A-Z]+" test.css。
我想有更好(更简洁)的方法。
【问题讨论】:
-
使用
str.scan..,str.scan(/p[A-Z]+/)