Ruby正则表达式"包含一个单词"

Dou*_*ugN 14 ruby regex

在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)

虽然速度差异在这里无关紧要,但正则表达式版本实际上更快.

  • 如果它是传闻而你自己没有验证过,你可能不应该在你的帖子中提及它并将其作为评论添加到其他帖子;-)我同意尽管`include?`实际上很好地传达了语义在任何情况下,性能差异应该可以忽略不计:-) (2认同)

JVK*_*JVK 6

在字符串中找到确切单词的正确解决方案是

the_body.match(/\bjoin\b/i) 或使用其他正则表达式:

(\W|^)join(\W|$)

请注意,我们需要查找字符串中是否存在“ join” WORD。所有上述解决方案将像字符串失败:they are joining canalsMy friend Bonjoiny is a cool guy