DougN
DougN

Reputation: 337

Ruby regex "contains a word"

In Ruby, how can I write a regex to inspect a submission for a single word?

Imagine I have a web form that that accepts text. I know if I want to see if the sentence --only-- contains "join" I can use

    if the_body == "join"

But that only works if the entire text submission is "join".

How do I catch a submission like this:

"I want to join your club?" or "Join me please"

Thanks!

Upvotes: 18

Views: 39181

Answers (3)

Michael Kohl
Michael Kohl

Reputation: 66867

You can do it with

string =~ /join/i
# /i makes it case insensitive

or

string.match(/join/i)

A little update regarding the performance comment:

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

While the speed difference really doesn't matter here, the regex version was actually faster.

Upvotes: 34

JVK
JVK

Reputation: 3912

Correct solution to find an exact WORD in a string is

the_body.match(/\bjoin\b/i) or use other regex:

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

Please note, we need to find whether "join" WORD exists or not in the string. All above solution will fail for strings like: they are joining canals or My friend Bonjoiny is a cool guy

Upvotes: 11

ksol
ksol

Reputation: 12265

There's no need for Regexp here -- String#include? will do the job.

Upvotes: -1

Related Questions