使用\ Q .. \ E时,preg_match如何处理定界符? [英] How the preg_match handles the delimiter when \Q..\E used?

查看:114
本文介绍了使用\ Q .. \ E时,preg_match如何处理定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式,并尝试了\ Q .. \ E转义序列.

I'm playing with regular expressions and I tried the \Q..\E escape sequence.

第一次尝试:

$regex = '/\Q http:// \E/';
var_dump(preg_match($regex, ' http:// '));

它告诉我'\'是未知修饰语,完全可以理解.

It tells me that '\' is unknown modifier, completely understandable.

第二次尝试:

$regex = '/\Q http:\/\/ \E/';
var_dump(preg_match($regex, ' http:// '));
var_dump(preg_match($regex, ' http:\/\/ '));

它运行,不匹配第一个字符串,但匹配第二个字符串.

It runs, not match the first string, but match the second one.

我知道我可以使用其他定界符或在没有\ Q .. \ E的情况下解决该问题,但是我很好奇它的工作原理.

I know that I could use other delimiter character or solve it without \Q..\E, but I'm curious that how it works.

我首先通过定界符将正则表达式与修饰符分开(必要时进行转义),然后正则表达式引擎解释\ Q .. \ E,但是当\ Q出现时,那么它就不会以相同的方式处理转义的定界符.

I through that at first it separates the regex from the modifiers by the delimiter (with handling the escaping if necessary) and after that the regex engine interprets the \Q..\E, but it seems like that when the \Q involved, then it not handles the escaped delimiter the same way.

在这种情况下到底会发生什么?

What happens exactly at this case?

谢谢!

推荐答案

\Q\E可用于忽略模式中的正则表达式元字符.

\Q and \E can be used to ignore regular expression metacharacters in the pattern.

例如,如果文字字符串包含定界符/,则正则表达式编译失败或匹配失败,因为它试图匹配用于对定界符进行转义的转义字符.在\Q \E之间的定界符应被视为文字字符,而不是定界符.

If the literal string contains the delimiter / for example, the regular expression compile fails or the match fails because it tries to match the escape character used to escape the delimiter. Delimiters that are between \Q \E should be treated as literal characters, not delimiters.

preg_match('~\Q http:// \E~', ' http:// ', $match);
var_dump($match);

# => array(1) { [0]=> string(7) " http:// " }

如果分隔符可能出现在\Q \E

Use preg_quote() instead of \Q \E if the delimiter may appear within \Q \E

$text = ' http:// ';

preg_match('/' . preg_quote($text, '/') . '/', $text, $match);
var_dump($match);

# => array(1) { [0]=> string(9) " http:// " }

这篇关于使用\ Q .. \ E时,preg_match如何处理定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆