Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find case-insensitive word matches in a line

Tags:

regex

ruby

I need to look for all occurrences of a word in a line, but the search must be case insensitive. What else do I need to add to my regular expression?

arr = line.scan(/\s+#{word}\s+/)
like image 209
Flethuseo Avatar asked Jan 06 '11 05:01

Flethuseo


1 Answers

You need modifier /i

arr = line.scan(/\b#{word}\b/i)

http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm

And better to use \b for word boundaries, because the second \s+ in your regex eats spaces, which may be used for the first \s+ of another matched word; also your regex fails on the beginning and the end of line:

> "asd asd asd asd".scan /\s+asd\s+/
=> [" asd "]
> "asd asd asd asd".scan /\basd\b/
=> ["asd", "asd", "asd", "asd"]
like image 63
Nakilon Avatar answered Sep 28 '22 08:09

Nakilon