1/04/2007

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} 是不是其他的值 . 原因是因為這樣可以增加效率的因素 .
  • /uunicode support
範例:

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

4. /u 就是 unicode support ,這裡有一個蠻好的實做方式可以做到 unicode 截字
  1. strs = str.scan(/./mu)
  2. strs[0,400].join
這裡面 /mu 就是 multiline 模式下使用 unicode 模式,先將他們拆成每個字一個 array ,然後再將array 前 400 個 element 取出來 join 成一個字串。


延伸閱讀



2 則留言:

gugod 提到...

您好,關於 /o 這個 modifier 你講錯了。請參考 http://www.regular-expressions.info/ruby.html 。以及以下這段程式碼:

a = "abc"
s = "foo abc abc"
["abc", "foo"].map { |a|
p = s =~ /#{a}/o;
print "#{a} => #{p}\n";
}

此段程式會印出

abc => 4
foo => 4

這兩列輸出,可知 /#{a}/o 的效果,在兩次執行期間,都等同於 /abc/。此效果也與 Perl 的 /o modifier 相符。是用來微調效率而產生的 modifier。

thegiive 提到...

您好 , 根據你的例子 , 我了解了我錯在哪裡了 . 非常的感謝 .