[英]Using arrays in regular expressions?
有誰知道是否有辦法在正則表達式中使用數組? 假設我想找出somefile.txt
包含數組的元素之一。 顯然,下面的代碼不起作用,但是是否有類似的東西起作用?
array = [thing1 thing2 thing3]
file = File.open("somefile.txt")
file.each_do |line|
if /array/.match(line)
puts line
end
基本上,我有一個文件,其中包含一個單詞列表,這些單詞需要在另一個大文件中用作搜索詞,並且我想避免這樣的事情:
($somefile =~ /(thing1|thing2|thing3)/)
您可以使用Regexp.union
,它返回與任何給定正則表達式匹配的Regexp
。 參數模式可以是String
或Regexp
:
Regexp.union(%w(thing1 thing2 thing3))
#=> /thing1|thing2|thing3/
要么
Regexp.union(/thing1/, /thing2/, /thing3/)
#=> /(?-mix:thing1)|(?-mix:thing2)|(?-mix:thing3)/
采用:
x = ['qwe', 'asd', 'zxc']
file = File.open("somefile.txt")
regexp = /(#{x.join '|'})/
file.each_do |line|
puts line if regexp.match(line)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.