这是我的做法:
files = %w[/xyz/abc.pl /xyz/def.rb /xyz/ghi.pl /xyz/jkl.rb /xyz/mno.pl foo.rb bar.pl /xyz/foo.java ]
files.grep(%r[/xyz/.+\.(?:rb|pl)$])
=> ["/xyz/abc.pl", "/xyz/def.rb", "/xyz/ghi.pl", "/xyz/jkl.rb", "/xyz/mno.pl"]
如果您不在乎路径是什么,请使用:
files.grep(%r[\.(?:rb|pl)$])
=> ["/xyz/abc.pl",
"/xyz/def.rb",
"/xyz/ghi.pl",
"/xyz/jkl.rb",
"/xyz/mno.pl",
"foo.rb",
"bar.pl"]
您说要匹配的文件名在日志文件中,但没有显示文件格式的示例。如果文件名位于行尾,则$
锚点将选择匹配项。如果文件名嵌入在行中,则删除$
锚。
这不适用于带有空格的文件路径:(
不修改最后一个示例代码,只添加一些带有嵌入空格的文件名,以及一些带有嵌入空格的路径:
files = %w[/xyz/abc.pl /xyz/def.rb /xyz/ghi.pl /xyz/jkl.rb /xyz/mno.pl foo.rb bar.pl /xyz/foo.java ]
files += [
'ruby file.rb',
'perl file.pl',
'/foo bar/ruby.rb',
'/foo bar/perl.rb'
]
files.grep(%r[\.(?:rb|pl)$])
在 IRB 中看起来像这样:
irb(main):008:0> files = %w[/xyz/abc.pl /xyz/def.rb /xyz/ghi.pl /xyz/jkl.rb /xyz/mno.pl foo.rb bar.pl /xyz/foo.java ]
[
[0] "/xyz/abc.pl",
[1] "/xyz/def.rb",
[2] "/xyz/ghi.pl",
[3] "/xyz/jkl.rb",
[4] "/xyz/mno.pl",
[5] "foo.rb",
[6] "bar.pl",
[7] "/xyz/foo.java"
]
irb(main):009:0> files += [
irb(main):010:1* 'ruby file.rb',
irb(main):011:1* 'perl file.pl',
irb(main):012:1* '/foo bar/ruby.rb',
irb(main):013:1* '/foo bar/perl.rb'
irb(main):014:1> ]
[
[ 0] "/xyz/abc.pl",
[ 1] "/xyz/def.rb",
[ 2] "/xyz/ghi.pl",
[ 3] "/xyz/jkl.rb",
[ 4] "/xyz/mno.pl",
[ 5] "foo.rb",
[ 6] "bar.pl",
[ 7] "/xyz/foo.java",
[ 8] "ruby file.rb",
[ 9] "perl file.pl",
[10] "/foo bar/ruby.rb",
[11] "/foo bar/perl.rb"
]
irb(main):015:0>
irb(main):016:0* files.grep(%r[\.(?:rb|pl)$])
[
[ 0] "/xyz/abc.pl",
[ 1] "/xyz/def.rb",
[ 2] "/xyz/ghi.pl",
[ 3] "/xyz/jkl.rb",
[ 4] "/xyz/mno.pl",
[ 5] "foo.rb",
[ 6] "bar.pl",
[ 7] "ruby file.rb",
[ 8] "perl file.pl",
[ 9] "/foo bar/ruby.rb",
[10] "/foo bar/perl.rb"
]
所以,是的,嵌入的空白也被处理了。
'/xyz/arb_path/abc.rb /xyz/arb_path/def.xml foo bar /xyz/arb_path/ghi.pl foo bar /xyz/arb_path/jkl.xml /xyz/arb_path/mno.rb'.split.grep(/\.(?:rb|pl)$/)
=> [
[0] "/xyz/arb_path/abc.rb",
[1] "/xyz/arb_path/ghi.pl",
[2] "/xyz/arb_path/mno.rb"
]