正则表达式两边带有感叹号('!\ d!') [英] Regular expression with exclamation marks on both sides ('!\d!')

查看:761
本文介绍了正则表达式两边带有感叹号('!\ d!')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在PHP preg_match函数中看到了正则表达式'!\d!'.这到底是什么?

I've seen the regular expression '!\d!' inside the PHP preg_match function. What the heck is this?

推荐答案

来自 PHP PCRE文档:

使用PCRE功能时,要求图案由定界符括起来.分隔符可以是任何非字母数字,非反斜杠,非空格字符.

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

在这种情况下,它只是使用!作为分隔符.如果要在正则表达式本身中使用普通定界符而不必对其进行转义,通常会使用它.在这种情况下,由于正则表达式的其余部分仅是\d,因此实际上不是必需的,但是它对于诸如检查路径是否包含三个以上目录级别之类的操作非常方便.您可以使用以下任何一种方式:

In this case, it's simply using ! as the delimiter. Often it's used if you want to use the normal delimiter within the regex itself without having to escape it. Not really necessary in this case since the rest of the regex is simply \d, but it comes in handy for things like checking that a path contains more than three directory levels. You can use either of:

/\/.*\/.*\/.*\/ blah blah blah /

或:

!/.*/.*/.*/ blah blah blah !

现在它们还没有经过彻底的测试,并且可能无法完全如广告中所述正常工作,但是您应该从最小的转义角度获得总体思路.

Now they haven't been tested thoroughly, and may not work entirely as advertised, but you should get the general idea re the minimal escaping required.

另一个示例(从链接到上面的页面)是检查字符串是否以http://标记开头.这两个:

Another example (from the page linked to above) is checking if a string starts with the http:// marker. Either of these two:

/^http:\/\//
!^http://!

就足够了,但是第二个更容易理解.

would suffice, but the second is easier to understand.

这篇关于正则表达式两边带有感叹号('!\ d!')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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