正则表达式中的波形符运算符

发布于 2024-07-23 02:46:09 字数 419 浏览 5 评论 0原文

我想知道正则表达式中波浪线运算符的含义是什么。

我有这样的声明:

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

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

它表示 =~ 是一个 Perl 运算符,意味着针对此正则表达式运行此变量。

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

早茶月光 2024-07-30 02:46:09

在本例中,它仅用作分隔符。

一般来说,在 PHP 中,正则表达式的第一个和最后一个字符是“分隔符”,用于标记匹配部分的开始和结束位置(如果您想在末尾添加修饰符,如 ungreedy 等),

通常 PHP 是这样工作的从字符串中作为正则表达式的第一个字符开始,匹配它的第二次出现作为第二个分隔符。 当文本中出现正常分隔符时(例如,文本中出现 /),这非常有用 - 这意味着您不必做尴尬的事情。

匹配“//”,分隔符设置为“/

<代码>/\/\//

匹配“//”和分隔符“#

<代码>#//#

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 "#"

#//#

热鲨 2024-07-30 02:46:09

在这种情况下,这没有任何意义。 它只是界定模式的开始和结束。 在 PCRE(Perl 兼容正则表达式)中,即在 PHP 中与 preg_* 一起使用的内容,模式是与表达式选项一起输入的,如下所示:

preg_match("/pattern/opt", ...);

但是,在本例中使用“/”作为分隔符是任意 - 尽管正斜杠很流行,但它可以用任何东西代替。 在你的例子中,它是波浪号。

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文