Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex "contains a word"

Tags:

regex

ruby

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!

like image 466
DougN Avatar asked Mar 19 '12 11:03

DougN


2 Answers

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.

like image 115
Michael Kohl Avatar answered Oct 05 '22 22:10

Michael Kohl


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

like image 23
JVK Avatar answered Oct 05 '22 22:10

JVK