ruby中的\z與\Z區別

c3tc3tc3t發表於2017-03-12
 1 s = "this is\nthe name\n"
 2 puts "--------------"
 3 puts s.match(/name\Z/)
 4 puts s.match(/name\z/)
 5 puts "--------------"
 6 
 7 s = "this is\nthe name"
 8 puts "--------------"
 9 puts s.match(/name\Z/)
10 puts s.match(/name\z/)
11 puts "--------------"
1 --------------
2 name
3 
4 --------------
5 --------------
6 name
7 name
8 --------------

 官方文件是

  • \Z - Matches end of string. If string ends with a newline, it matches just before newline

  • \z - Matches end of string

我的理解是\Z和\z都是匹配字串的結尾,但是如果字串結尾多了一個\n,那麼\Z匹配時忽略這個\n,匹配\n前面的內容是否與給定的正則匹配,而\z不能忽略,所以\z會失敗,如上面例子

相關文章