php 正则表达式中的波浪号运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/938100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tilde operator in Regular expressions
提问by Keira Nighly
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.
它说这=~是一个 perl 运算符,这意味着针对这个正则表达式运行这个变量。
But why does my regular expression contains two tilde operators?
但是为什么我的正则表达式包含两个波浪号运算符?
回答by Mez
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)
通常,在 PHP 中,正则表达式的第一个和最后一个字符是“分隔符”,用于标记匹配部分的开始和结束位置(以防您想在末尾添加修饰符,例如 ungreedy 等)
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.
通常 PHP 从字符串中的第一个字符开始计算,该字符表示正则表达式,匹配它的第二次出现作为第二个分隔符。当您在文本中出现正常分隔符时(例如,/在文本中出现 ),这很有用 - 这意味着您不必做尴尬的事情。
Matching for "//" with the delimiter set to "/"
匹配“ //”,分隔符设置为“ /”
/\/\//
/\/\//
Matching for "//" with the delimiter of "#"
匹配的“ //”用分隔符“ #”
#//#
#//#
回答by Nick
In this case, it doesn't mean anything. It is simply delimiting the start and end of your pattern. In PCRE (Perl Compatible Regular Expressions), which is what you're using with preg_* in PHP, the pattern is input along side the expression options, like so:
在这种情况下,它没有任何意义。它只是分隔模式的开始和结束。在 PCRE(Perl 兼容的正则表达式)中,您在 PHP 中使用 preg_* 时,模式与表达式选项一起输入,如下所示:
preg_match("/pattern/opt", ...);
However, the use of "/" as the delimiter in this case is arbitrary - although forward slash is popular, it can be replaced with anything. In your case, it's tilde.
然而,在这种情况下使用“/”作为分隔符是任意的——尽管正斜杠很流行,但它可以被任何东西替换。在你的情况下,它是波浪号。

