正则表达式末尾的“i”是什么意思?

时间:2012-01-19 08:22:54

标签: ruby regex

%r{\.(gif|jpg|png)$}i

一行末尾的i是什么意思?我知道%r表示正则表达式,但这里的“我”是什么?

我最初尝试在Google上搜索,但很难找到有关这件小事的信息。

2 个答案:

答案 0 :(得分:4)

i修饰符表示正则表达式在匹配文本时会忽略大小写。您可以阅读有关其他正则表达式修饰符here的更多信息。

# with i modifier
%r{.(gif|jpg|png)$}i === ".JpG" #=> true 
%r{.(gif|jpg|png)$}i === ".jpg" #=> true 

# without i modifier
%r{.(gif|jpg|png)$} === ".JpG" #=> false
%r{.(gif|jpg|png)$} === ".jpg" #=> true  

注意:正则表达式中的.表示“除换行符之外的任何单个字符”,而不是“点字符”。如果您需要匹配点字符,请使用反斜杠来转义它:\.

%r{.(gif|jpg|png)$} === "ajpg"  # => true
%r{\.(gif|jpg|png)$} === "ajpg" # => false
%r{\.(gif|jpg|png)$} === ".jpg" # => true

答案 1 :(得分:0)

Ruby附带ri,它是Ruby的文档的本地副本。

打开终端窗口或控制台,然后输入ri Regexp,您将获得Regexp的文档。仔细阅读它,你会发现:

== Options

The end delimiter for a regexp can be followed by one or more single-letter
options which control how the pattern can match.

* /pat/i - Ignore case
* /pat/m - Treat a newline as a character matched by .
* /pat/x - Ignore whitespace and comments in the pattern
* /pat/o - Perform #{} interpolation only once

i, m, and x can also be applied on the subexpression level with the
(?on-off) construct, which enables options on, and disables
options off for the expression enclosed by the parentheses.

        /a(?i:b)c/.match('aBc') #=> #
        /a(?i:b)c/.match('abc') #=> #