正则表达式中的Tilde运算符 [英] Tilde operator in Regular expressions

查看:118
本文介绍了正则表达式中的Tilde运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道正则表达式中波浪符的含义是什么.

我有这句话:

if (!preg_match('~^\d{10}$~', $_POST['isbn'])) {
    $warnings[] = 'ISBN should be 10 digits';
}

我发现此文档解释了波浪号的含义: ~

它说=~是一个perl运算符,表示对该正则表达式运行此变量.

但是为什么我的正则表达式包含两个波浪号运算符?

解决方案

在这种情况下,它只是用作分隔符.

通常,在PHP中,正则表达式的第一个和最后一个字符是定界符",用于标记匹配部分的开始和结束位置(以防您想在末尾添加修饰符,例如不满意等). /p>

通常,PHP从作为正则表达式的字符串中的第一个字符开始解决此问题,并将其第二次出现与第二个分隔符匹配.在文本中出现普通定界符的情况下(例如,文本中出现/的情况),这很有用-这意味着您不必做笨拙的事情.

在分隔符设置为"/"的情况下匹配"//"

/\/\//

使用分隔符"#"匹配"//"

#//#

I want to know what's the meaning of tilde operator in regular expressions.

I have this statement:

if (!preg_match('~^\d{10}$~', $_POST['isbn'])) {
    $warnings[] = 'ISBN should be 10 digits';
}

I found this document explaining what tilde means: ~

It said that =~ is a perl operator that means run this variable against this regular expression.

But why does my regular expression contains two tilde operators?

解决方案

In this case, it's just being used as a delimiter.

Generally, in PHP, the first and last characters of a regular expression are "delimiters" to mark the start and ending position of a matching portion (in case you want to add modifiers at the end, like ungreedy, etc)

Generally PHP works this out from the first character in a string that is meant as a regular expression, matching the second occurence of it as the second delimiter. This is useful where you have an occurrence of the normal delimiter in the text (for example, occurences of / in the text) - this means you don't have to do awkward things.

Matching for "//" with the delimiter set to "/"

/\/\//

Matching for "//" with the delimiter of "#"

#//#

这篇关于正则表达式中的Tilde运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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