在Ruby中,我如何编写正则表达式来检查单个单词的提交?
想象一下,我有一个接受文本的网络表单.我知道如果我想查看句子--only--是否包含"join"我可以使用
if the_body == "join"
Run Code Online (Sandbox Code Playgroud)
但这只有在整个文本提交是"加入"时才有效.
我如何捕获这样的提交:
"我想加入你的俱乐部?" 或"请加入我"
谢谢!
Mic*_*ohl 31
你可以做到
string =~ /join/i
# /i makes it case insensitive
Run Code Online (Sandbox Code Playgroud)
要么
string.match(/join/i)
Run Code Online (Sandbox Code Playgroud)
关于性能评论的一点点更新:
>> s = "i want to join your club"
>> n = 500000
=> 500000
>> Benchmark.bm do |x|
.. x.report { n.times { s.include? "join" } }
.. x.report { n.times { s =~ /join/ } }
.. end
user system total real
0.190000 0.000000 0.190000 ( 0.186184)
0.130000 0.000000 0.130000 ( 0.135985)
Run Code Online (Sandbox Code Playgroud)
虽然速度差异在这里无关紧要,但正则表达式版本实际上更快.
在字符串中找到确切单词的正确解决方案是
the_body.match(/\bjoin\b/i)
或使用其他正则表达式:
(\W|^)join(\W|$)
请注意,我们需要查找字符串中是否存在“ join” WORD。所有上述解决方案将像字符串失败:they are joining canals
或My friend Bonjoiny is a cool guy
归档时间: |
|
查看次数: |
29511 次 |
最近记录: |