有没有办法/func:\[sync\] displayPTS/
从字符串创建正则表达式func:[sync] displayPTS
?
这个问题背后的故事是我有一个serval字符串模式来搜索文本文件,我不想一次又一次地写同样的东西.
File.open($f).readlines.reject {|l| not l =~ /"#{string1}"/}
File.open($f).readlines.reject {|l| not l =~ /"#{string2}"/}
Run Code Online (Sandbox Code Playgroud)
相反,我希望有一个功能来完成这项工作:
def filter string
#build the reg pattern from string
File.open($f).readlines.reject {|l| not l =~ pattern}
end
filter string1
filter string2
Run Code Online (Sandbox Code Playgroud)
Bob*_*man 25
s = "func:[sync] displayPTS"
# => "func:[sync] displayPTS"
r = Regexp.new(s)
# => /func:[sync] displayPTS/
r = Regexp.new(Regexp.escape(s))
# => /func:\[sync\]\ displayPTS/
Run Code Online (Sandbox Code Playgroud)
tre*_*son 13
我喜欢鲍勃的回答,但只是为了节省键盘上的时间:
string = 'func:\[sync] displayPTS'
/#{string}/
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9527 次 |
最近记录: |