简体   繁体   中英

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

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

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

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

file 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.

Use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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