关于ruby:检查数组元素是否在线

Check if array element appears on line

我一行一行地检查一个文件,我想检查该行是否包含数组中的任何元素。例如,如果我有:

1
myArray = ["cat","dog","fish"]

现在的那条线说:

I love my pet dog

输出会说

Found a line containing array string

这是我有的,但不起作用。

1
2
3
4
myArray = ["cat","dog","fish"]
File.open('file.txt').each_line { |line|
  puts"Found a line containing array string" if line =~ myArray  #need to fix this logic
}

我试过include?any?,但不知道我是否使用正确。

更新::我遗漏了一个重要的部分。我需要精确的匹配!所以我不希望这句话在不准确的情况下返回真。例如,如果我的行中说"我爱我的宠物狗",那么这个语句应该返回false,因为"狗"在数组中。不是"小狗"

我在澄清错误上的错误


您必须分别检查数组中的每个字符串,并使用\b来匹配单词边界,以确保您只获得完整的单词:

1
2
3
4
5
6
7
strings = ["cat","dog","fish"].map { |s| Regexp.quote(s) }

File.open('file.txt').each_line do |line|
  strings.each do |string|
    puts"Found a line containing array string" if line =~ /\b#{string}\b/
  end
end

或者构建regex:

1
2
3
4
5
6
strings = ["cat","dog","fish"].map { |s| Regexp.quote(s) }
pattern = /\b(#{strings.join('|')})\b/

File.open('file.txt').each_line do |line|
  puts"Found a line containing array string" if line =~ pattern
end

调用Regexp.quote可防止正则表达式中有意义的字符产生意外的效果。


可以使用数组创建regex

1
2
3
4
myArray = ["cat","dog","fish"]
File.open('file.txt').each_line { |line|
  puts"Found a line containing array string" if %r(#{myArray.join('|')}) === line
}


1
2
3
4
myArray = ["cat","dog","fish"]
File.open('file.txt').each_line { |line|
  puts"Found a line containing array string" if myArray.any? { |word| /.*#{word}.*/.match? line}
}

未测试代码


1
2
3
4
5
arr = ['cat', 'dog', 'fish']

File.open('file.txt').each_line do |line|
  puts 'Found a line containing key word' if arr.any? { |e| line.include? e }
end

检测为字而不是子字符串:

line =~ /(#{e}|.*\s#{e})([\s.,:;-].*|
)/

还有一个有趣的解决方案:

1
2
3
4
5
arr = ['cat', 'dog', 'fish']

File.open('file.txt').each_line do |line|
  puts 'Found a line containing array string' if !(line.split(/[\s,.:;-]/) & arr).empty?
end