Find case-insensitive word matches in a line

后端 未结 1 1697
广开言路
广开言路 2021-01-04 06:58

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 =          


        
相关标签:
1条回答
  • 2021-01-04 07:37

    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"]
    
    0 讨论(0)
提交回复
热议问题