在ruby中,使用^和$匹配行首和行尾(并不是字符串开头和结尾)
例:
string =
"abc\ndef\nghi" ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /^abc/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /abc$/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /^def/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /def$/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /^ghi/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi$/=~
string abc
def
ghi
0
0
4
4
8
8
------
\A和\Z匹配字符串本身的开头和末尾
string =
"abc\ndef\nghi" ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /\Aa/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /\Adef/=~
string ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi\Z/=~
string0
nil
8
---
\z和\Z相同,但\Z 与最后一个换行前匹配,而\z必须显式地匹配
string =
"abc\ndef\nghi" ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
str2=
"abc\ndef\nghi\n" ![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi\Z/ =~ str2 # 8
![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi\Z/=~
string #8
![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi\z/ =~
string # 8
![ruby正则表达式使用锚点](https://s1.51cto.com/images/editer/InBlock.gif)
puts /ghi\z/ =~str2 # nil
网站栏目:ruby正则表达式使用锚点
本文链接:https://www.cdcxhl.com/article40/jgsgeo.html
成都网站建设公司_创新互联,为您提供搜索引擎优化、网站改版、手机网站建设、App设计、外贸建站、做网站
广告
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源:
创新互联