2012-01-19 43 views
-1
%r{\.(gif|jpg|png)$}i 

i在行尾是什麼意思?我知道%r是指正則表達式,但這裏的「我」是什麼?正則表達式結尾處的「i」是什麼意思?

我試着先在Google上搜索,但是很難找到關於這個小東西的信息。

+0

我有同樣的問題,這是第一個谷歌的結果。格式是唯一可能的原因,因爲我提出了編輯來清理它。 –

+0

@MatthewRead:良好的調用,但你可以做得更好,並在適用時使用[代碼格式化](http://stackoverflow.com/editing-help#code),特別是涉及正則表達式時。 –

回答

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 
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') #=> # 
相關問題