简体   繁体   English

为什么这种未转义的正则表达式模式有效?

[英]Why does this unescaped regex pattern work?

I've come through a lot of articles and even questions on SO which state that that in PHP, because of the fact that regular expressions are represented using strings, you must escape all backslashes. 我已经经历了很多文章甚至是关于SO的问题,这些文章指出在PHP中,由于正则表达式使用字符串表示,因此必须转义所有反斜杠。 But for some reason, the following returns true without failing: 但由于某种原因,以下返回true而不会失败:

preg_match('/^\w+\d+$/','abcdef123456')

How come it works if I'm supposed to escape the \\ s? 为什么它的工作原理,如果我应该逃避\\ S' It seems unnecessary, but then why does everyone say otherwise? 这似乎没必要,但那为什么每个人都这么说呢?

According to PHP String - Manual - Single quoted : 根据PHP字符串 - 手册 - 单引号

To specify a literal single quote, escape it with a backslash (\\). 要指定文字单引号,请使用反斜杠(\\)对其进行转义。 To specify a literal backslash, double it (\\\\). 要指定文字反斜杠,请将其加倍(\\\\)。 All other instances of backslash will be treated as a literal backslash : this means that the other escape sequences you might be used to, such as \\r or \\n, will be output literally as specified rather than having any special meaning. 反斜杠的所有其他实例将被视为文字反斜杠 :这意味着您可能习惯使用的其他转义序列(如\\ r或\\ n)将按字母顺序输出,而不是具有任何特殊含义。

Because you're using single quotes. 因为你使用的是单引号。 In fact, with double quotes it doesn't matter here because \\w has no special meaning in a PHP string and therefor is left as \\w . 实际上,使用双引号并不重要,因为\\w在PHP字符串中没有特殊含义,因此保留为\\w

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM