有没有办法从字符串 func:[sync] displayPTS
创建正则表达式 /func:\[sync\] displayPTS/
?
这个问题背后的故事是我有多个字符串模式可以在文本文件中搜索,我不想一次又一次地写同样的东西。
File.open($f).readlines.reject {|l| not l =~ /"#{string1}"/}
File.open($f).readlines.reject {|l| not l =~ /"#{string2}"/}
相反,我想要一个函数来完成这项工作:
def filter string
#build the reg pattern from string
File.open($f).readlines.reject {|l| not l =~ pattern}
end
filter string1
filter string2
最佳答案
s = "func:[sync] displayPTS"
# => "func:[sync] displayPTS"
r = Regexp.new(s)
# => /func:[sync] displayPTS/
r = Regexp.new(Regexp.escape(s))
# => /func:\[sync\]\ displayPTS/
关于ruby - 从字符串创建正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2004688/