簡體   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