在Ruby中,我如何编写正则表达式来检查提交的单词?
假设我有一个接受文本的Web表单。如果我想要查看句子是否--仅--包含"join",我可以使用:
if the_body == "join"
但仅当整个文本提交为"join"时才有效。
我如何捕获这样的提交:
"我想加入你的俱乐部?" 或者 "请加入我"
谢谢!
string =~ /join/i
# /i makes it case insensitive
或者string.match(/join/i)
关于性能评论的一点更新:
>> 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)
虽然速度差异在这里并不重要,但正则表达式版本实际上更快。
String#include?
最后使用了Rabin-Karp算法,其最坏情况下的性能为O(mn),而一个合适的正则表达式引擎可能可以在O(n)内完成此操作。 - Michael Kohlinclude?
实际上非常好地传达了语义,而且性能差异在任何情况下都应该是可以忽略不计的 :-) - Michael Kohl找到字符串中确切单词的正确方法是:
the_body.match(/\bjoin\b/i)
或使用其他正则表达式:
(\W|^)join(\W|$)
请注意,我们需要找出字符串中是否存在“join”这个单词。以上所有解决方案都无法适用于以下字符串:they are joining canals
或 My friend Bonjoiny is a cool guy
String#include?
就可以完成工作。