`

Ruby 的 Regualr Expression Modifier

阅读更多
Ruby的 Regular Expression Pattern 是參照 Perl 的模式的,他的格式分為
/pattern/modifiers

pattern 就是 regular 的 matching pattern,這裡的部分 Programming Ruby 介紹很多了,所以就不再介紹了。而 modifier 就是一些重要的選項,主要分為
  • /i :大小寫 case insensitive
  • /m :原本是只 match 單行, m就是開到多行模式
  • /o : 當 matching pattern 裡面有 #{variable_name} 變數的時候 , 他只會產生一次 regex object , 隻後如果有重複利用到這個 regex object 的時候 , 他會直接利用原來的 object , 而不會判斷裡面的 #{variable_name} 是不是其他的值 . 原因是因為這樣可以增加效率的因素 .
範例:

1. case insensitive
irb(main):020:0> puts 'Match' if 'AbC' =~ /abc/
=> nil
irb(main):020:0> puts 'Match' if 'AbC' =~ /abc/i
Match
=> nil

2. 多行模式
irb(main):033:0> puts 'Match' if "abc\nd" =~ /a.*d/
=> nil
irb(main):034:0> puts 'Match' if "abc\nd" =~ /a.*d/m
Match
=> nil
3. /o 比較難理解 , 我第一次也理解錯誤了 . 幸好有 gugod 指証 , 再次感謝 . 這個例子改自 gugod 提供的例子 , 我覺得會比較清楚情況如何 .
["abc", "foo"].map do |a|
regex = /#{a}/o
puts "regex object id with o modifier is #{regex.object_id} and content is #{regex.inspect}\n"
end

["abc", "foo"].map do |a|
regex_no_o = /#{a}/
print "regex object id without o modifier is #{regex_no_o.object_id} and content is #{regex_no_o.inspect}\n"
end
出現訊息如下
regex object id with o modifier is -605885768 and content is /abc/
regex object id with o modifier is -605885768 and content is /abc/
regex object id without o modifier is -605885898 and content is /abc/
regex object id without o modifier is -605885958 and content is /foo/

有 o 的 regex 雖然變數 a 改變了 , 但是 object_id 依舊相同 , 內容也是一樣的 , 證明有 o 的 regex 不會更改其內容 . 但是預設的 regex 還是會重新產生一個新的 regex

延伸閱讀


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics