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

延伸閱讀

Programming Ruby
How to Use Ruby Regular Expression

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值