Ruby 正則表達式是強大的字串模式比對工具。本文涵蓋字面值語法、修飾符、常用模式元字元、sub/gsub 搜尋替換方法,並提供實際範例。
/pattern/
/pattern/im # 修飾符
%r{/usr/local} # 任意分隔符
| 修飾符 | 說明 |
|---|---|
i | 忽略大小寫 |
m | 多行模式(. 匹配換行) |
x | 延伸語法(忽略空白、允許註解) |
o | 只插值一次 |
^ $:行首/行尾. * + ?:任意字元、零或多、一或多、零或一[] [^]:字元類別、排除類別():分組捕獲|:或\d \w \s:數字、單字字元、空白line1 = "Cats are smarter than dogs"
line2 = "Dogs also like meat"
if line1 =~ /Cats(.*)/
puts "Line1 starts with Cats"
end
# => Line1 starts with Cats
phone = "2004-959-559 #This is Phone Number"
# 刪除註解
phone.sub!(/#.*$/, "")
puts phone # 2004-959-559
# 只保留數字
phone.gsub!(/\D/, "")
puts phone # 2004959559
text = "rails are rails, really good Ruby on Rails"
text.gsub!("rails", "Rails")
text.gsub!(/\brails\b/, "Rails")
puts text # Rails are Rails, really good Ruby on Rails
注意: sub!/gsub! 就地修改字串;sub/gsub 回傳新字串。