ruby正则表达式使用锚点
在ruby中,使用^和$匹配行首和行尾(并不是字符串开头和结尾)
例:
string = "abc\ndef\nghi"
puts string
puts /^abc/=~string
puts /abc$/=~string
puts /^def/=~string
puts /def$/=~string
puts /^ghi/=~string
puts /ghi$/=~string
puts string
puts /^abc/=~string
puts /abc$/=~string
puts /^def/=~string
puts /def$/=~string
puts /^ghi/=~string
puts /ghi$/=~string
abc
def
ghi
0
0
4
4
8
8
------
def
ghi
0
0
4
4
8
8
------
\A和\Z匹配字符串本身的开头和末尾
string = "abc\ndef\nghi"
puts /\Aa/=~string
puts /\Adef/=~string
puts /ghi\Z/=~string
puts /\Aa/=~string
puts /\Adef/=~string
puts /ghi\Z/=~string
0
nil
8
---
nil
8
---
\z和\Z相同,但\Z 与最后一个换行前匹配,而\z必须显式地匹配
string = "abc\ndef\nghi"
str2="abc\ndef\nghi\n"
puts /ghi\Z/ =~ str2 # 8
puts /ghi\Z/=~string #8
puts /ghi\z/ =~string # 8
puts /ghi\z/ =~str2 # nil
str2="abc\ndef\nghi\n"
puts /ghi\Z/ =~ str2 # 8
puts /ghi\Z/=~string #8
puts /ghi\z/ =~string # 8
puts /ghi\z/ =~str2 # nil
网页标题:ruby正则表达式使用锚点
当前网址:http://pwwzsj.com/article/jgsgeo.html