使用方法
使用quote方法的正则表达式
转义正则表达式中的所有元字符
re1 = Regexp.new("abc*def")
re2 = Regexp.new(Regexp.quote("abc*def"))
p re1 =~ "abc*def"
#=> nil
p re2 =~ "abc*def"
#=> 0
正则表达式的选项
选项 | 选项常量 | 意义 |
---|---|---|
i | Regexp::IGNORECASE | 不区分大小写 |
x | Regexp::EXTENDED | 忽略模式中的空白字符 |
m | Regexp::MULTILINE | 匹配多行 |
o | 无 | 只使用一次内嵌表达式 |
例子
str = "ABC\nDEF\nGHI"
p /DEF.GHI/ =~ str
#=> nil
p /DEF.GHI/m =~ str
#=> 4
/Ruby/i
#等价于
Regexp.new("Ruby", Regexp::IGNORECASE)
捕获
/(.)(.)(.)/ =~ "abc"
p $1 #=> "a"
p $2 #=> "b"
p $3 #=> "c"
/(.)(\d\d)+(.)/ =~ "123456"
p $1 #=> "1"
p $2 #=> "45"
p $3 #=> "6"
#?:过滤掉不需要的捕获
/(.)(?:\d\d)+(.)/ =~ "123456"
p $1 #=> "1"
p $2 #=> "6"
/C./ =~ /ABCDEF/
#匹配部分前的字符串
p $` #=> "AB"
#匹配部分的字符串
p $& #=> "CD"
#匹配部分后的字符串
p $' #=> "DE"
正则表达式的方法
方法 | 意义 |
---|---|
sub | 替换首次匹配的部分 |
gsub | 替换所有匹配的部分 |
scan | 类似gsub,获取所有匹配的部分,但不能做置换操作 |
sub
gsub
sub!
gsub!
str = "abc def g hi"
#将第一个空格去掉
p str.sub(/\s+/, '')
#=> "abcdef g hi"
#将所有的空格去掉
p str.gsub(/\s+/, '')
#=> "abcdefghi"
如果使用块,会将匹配部分传给块,块返回的字符串会替换字符串匹配部分
str = "abracatabra"
nstr = str.sub(/.a/) do |matched|
'<' + matched.upcase + '>'
end
p nstr
#=> "ab<RA>catabra"
nstr = str.gsub(/.a/) do |matched|
'<' + matched.upcase + '>'
end
p nstr
#=> "ab<RA><CA><TA>b<RA>"
scan
str = "abracatabra"
nstr = str.scan(/.a/) do |matched|
p matched
end
#=> "ra"
#=> "ca"
#=> "ta"
#=> "ra"
str = "abracatabra"
nstr = str.scan(/(.)(a)/) do |matched|
p matched
end
#=> ["r", "a"]
#=> ["c", "a"]
#=> ["t", "a"]
#=> ["r", "a"]
str = "abracatabra"
nstr = str.scan(/(.)(a)/) do |a, b|
p a+"-"+b
end
#=> "r-a"
#=> "c-a"
#=> "t-a"
#=> "r-a"
str = "abracatabra"
p str.scan(/(.)(a)/)
#=> ["ra", "ca", "ta", "ra"]