繁体   English   中英

Ruby 匹配多个字符串正则表达式

[英]Ruby match multiple string Regex

我正在尝试增强下面的脚本,以仅打印目录中文件列表中 *) 6 个字符的唯一值 - 字母数字和小写或 *) 以 map 开头的单词

我试过的

values = []
@files = Dir.glob("*.txt")
for values in @files
 file = File.read(values)
 file.split(' ').each do |line|
    values.push(line.gsub(',', '')) if line.match(/[a-z0-9]{6}/) end or unless values.include? line.gsub(',', '') or line.match(/map_.*/)
  end
end

puts values

例子,

文件 1

[id]
col1 = map_dr_check, map_iop, foo123
col2 = bar123, FOO123
col3 = ta2ngo, bar123

[/id_check]
@col2 = dr
@col1 = r

档案 2

[id]
col1 = map_dr_check, map_iop, foo123
col2 = alp23r
col3 = poi90k, bar123

[/id_check]
@col2 = *
@col1 = r

预期输出

map_dr_check
map_iop
foo123
ta2ngo
bar123
alp23r
poi90k

但是我的输出是空的,我不确定我的正则表达式哪里出了问题,或者字符串是否支持 .match 方法。

使用Enumerable#grep

input = ... # get it from files, or whatever
input.split.grep(/\A[[:alnum:]]{6}\z|\Amap_.*/)

对于您的示例(未经测试):

Dir.glob("*.txt").flat_map do |file|
  File.read(file).split.grep(/\A[[:alnum:]]{6}\z|\Amap_.*/)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM