为什么Ruby的正则表达式使用和\ \ z ^和$ ?

时间:2021-08-16 00:14:15

I'm not a Ruby programmer, but as I was reading through the extensive Ruby on Rails security guide, I noticed this section:

我不是一个Ruby程序员,但是当我阅读了大量的Ruby on Rails安全指南时,我注意到了这个部分:

A common pitfall in Ruby’s regular expressions is to match the string’s beginning and end by ^ and $, instead of \A and \z.

Ruby的一个常见陷阱的正则表达式来匹配字符串的开始和结束^和$,而不是\ \ z。

Does anyone know if this is this just a matter of aesthetics or something else? I ask because I've only used languages that use ^ and $.

有人知道这只是美学问题还是别的什么?我问,因为我只使用^和$的使用语言。

1 个解决方案

#1


50  

This isn't specific to Ruby; \A and \Z are not the same thing as ^ and $. ^ and $ are the start and end of line anchors, whereas \A and \Z are the start and end of string anchors.

这不是Ruby特有的;A和\ \ Z ^和$不是一回事。^和$的开始和结束行锚,而\ \ Z和锚的开始和结束字符串。

Ruby differs from other languages in that it automatically uses "multiline mode" (which enables the aforementioned behaviour of having ^ and $ match per line) for regular expressions, but in most other flavours you need to enable it yourself, which is probably why that article contains the warning.

Ruby与其他语言的不同之处在于,它会自动使用“多行模式”(使上述行为的^和$匹配每行)的正则表达式,但在大多数其他口味你需要使它自己,这可能是为什么这篇文章包含了警告。

Reference: http://www.regular-expressions.info/anchors.html

参考:http://www.regular-expressions.info/anchors.html

#1


50  

This isn't specific to Ruby; \A and \Z are not the same thing as ^ and $. ^ and $ are the start and end of line anchors, whereas \A and \Z are the start and end of string anchors.

这不是Ruby特有的;A和\ \ Z ^和$不是一回事。^和$的开始和结束行锚,而\ \ Z和锚的开始和结束字符串。

Ruby differs from other languages in that it automatically uses "multiline mode" (which enables the aforementioned behaviour of having ^ and $ match per line) for regular expressions, but in most other flavours you need to enable it yourself, which is probably why that article contains the warning.

Ruby与其他语言的不同之处在于,它会自动使用“多行模式”(使上述行为的^和$匹配每行)的正则表达式,但在大多数其他口味你需要使它自己,这可能是为什么这篇文章包含了警告。

Reference: http://www.regular-expressions.info/anchors.html

参考:http://www.regular-expressions.info/anchors.html