I want a regular expression that will extract the words happy and good, both non greedy and both case insensitive.
@a = [" I am very HAppy!!", "sad today..", "happy. to hear about this..", "the day is good", "sad one", "sad story"]
It looks like this works with one word:
@z = @a.join.scan(/\bhappy\b/i)
But when I add in good it does not work as I expect.
@z = @a.join.scan(/\bhappy|good\b/i)
Expect ( happy 2x and good 1x):
@z.size => 3
The result it gives me:
@z.size => 2
You should add parentheses around your alternation so that the
\bs will apply to eitherhappyorgoodas a unit:Then, you probably want to scan each element of the
@aarray rather than@a.joinso amapandflattenare called for:You could also use a non-capturing group:
but it won’t make any difference in this case.