需要匹配PHP正则表达式中的多个反斜杠
问题描述:
I'm trying to match 4 backslahes using preg_match.
preg_match('/\\\\\\\\/',$subject)
works fine, but preg_match('/\\{4}/',$subject)
doesn't.
Perhaps I'm using {} incorrectly. Could anyone advise?
我正在尝试使用preg_match匹配4个后退。 p>
也许我错误地使用了{}。 有人可以建议吗? p>
div> preg_match('/ \\\\\\\\ /',$ subject) code>工作正常,但
preg_match('/ \\ {4} /',$ subject) code>不行 't。 p>
答
Ok I got it: Two backslashes mean you want one backslash in your string: So for the regex it looks like this: /\{4}/
Which means you want to escape the {
What you need here is:
preg_match('/\\\\{4}/', $subject);
That looks for the regex like this: /\\{4}/
and works properly.
答
Use this:
preg_match('/(?:\\\\){2}/',$subject, $m);
It matches 4 backslashes.
答
Regex is the wrong tool when you're looking for a literal string.
strpos($subject, str_repeat("\\",4)) !== false