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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With