在一行中查找不区分大小写的单词匹配 [英] Find case-insensitive word matches in a line

查看:43
本文介绍了在一行中查找不区分大小写的单词匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查找一行中出现的所有单词,但搜索必须不区分大小写.我还需要在正则表达式中添加什么?

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+/)

推荐答案

你需要修饰符 /i

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

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

最好使用 \b 作为单词边界,因为正则表达式中的第二个 \s+ eats 空格,这可能用于另一个匹配词的第一个 \s+ ;您的正则表达式在行首和行尾也失败:

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"]

这篇关于在一行中查找不区分大小写的单词匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆