在正则表达式中转义反斜杠[\]的正确方法? [英] Right way to escape backslash [ \ ] in PHP regex?
问题描述
出于好奇,我试图找出哪种正则转义反斜杠的正确方法,以用于PHP正则表达式模式,如下所示:
Just out of curiosity, I'm trying to figure out which exactly is the right way to escape a backslash for use in a PHP regular expression pattern like so:
测试01:(3个反斜线)
$pattern = "/^[\\\]{1,}$/";
$string = '\\';
// ----- RETURNS A MATCH -----
测试02:(4个反斜杠)
$pattern = "/^[\\\\]{1,}$/";
$string = '\\';
// ----- ALSO RETURNS A MATCH -----
根据下面的文章,4应该是正确的方法,但令我困惑的是两个测试都返回了一个匹配项.如果两者都正确,那么4是首选方式吗?
According to the articles below, 4 is supposedly the right way but what confuses me is that both tests returned a match. If both are right, then is 4 the preferred way?
资源:
- http://www.developwebsites.net/match-backslash-preg_match-php/
- Can't escape the backslash with regex?
推荐答案
问题是,您正在使用字符类[]
,因此嵌入多少个文字反斜杠都没有关系,会被当作一个反斜杠.
The thing is, you're using a character class, []
, so it doesn't matter how many literal backslashes are embedded in it, it'll be treated as a single backslash.
例如以下两个正则表达式:
e.g. the following two regexes:
/[a]/
/[aa]/
就正则表达式引擎而言,
在所有意图和目的上都是相同的.字符类采用一个字符列表,然后将它们折叠"下来以匹配单个字符,并遵循对于正在考虑的当前字符,[]
内是否列出了任何字符?".如果您在该类中列出了两个反斜杠,那么它将是字符是一个反斜杠还是一个反斜杠?".
are for all intents and purposes identical as far as the regex engine is concerned. Character classes take a list of characters and "collapse" them down to match a single character, along the lines of "for the current character being considered, is it any of the characters listed inside the []
?". If you list two backslashes in the class, then it'll be "is the char a blackslash or is it a backslash?".
这篇关于在正则表达式中转义反斜杠[\]的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!