简体   繁体   English

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

[英]Ruby match multiple string Regex

I'm trying to enhance my script below to print only the unique values that shud be of *) 6 characters - alphanumeric and in lowercase or *) words starting with map ,from the list of files in a directory我正在尝试增强下面的脚本,以仅打印目录中文件列表中 *) 6 个字符的唯一值 - 字母数字和小写或 *) 以 map 开头的单词

What I've tried我试过的

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

Example,例子,

file 1文件 1

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

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

file 2档案 2

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

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

Expected output预期输出

map_dr_check
map_iop
foo123
ta2ngo
bar123
alp23r
poi90k

but my output is empty and I'm not sure where I've gone wrong with my regex or whether the .match method is supported with string.但是我的输出是空的,我不确定我的正则表达式哪里出了问题,或者字符串是否支持 .match 方法。

Use Enumerable#grep :使用Enumerable#grep

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

For your example (untested):对于您的示例(未经测试):

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