gpt4 book ai didi

javascript - PHP 正则表达式和 javascript 正则表达式有什么区别

转载 作者:可可西里 更新时间:2023-11-01 02:08:28 25 4
gpt4 key购买 nike

我在正则表达式中工作,我的正则表达式是 /\[([^]\s]+).([^]]+)\]/g 这在 PHP 中非常适用于 [http://sdgdssd.com fghdfhdhhd]但是当我将此正则表达式用于 javascript 时,它与此输入字符串不匹配

我的输入是[http://sdgdssd.com fghdfhdhhd]

最佳答案

在 JavaScript 正则表达式中,您必须始终转义字符类中的 ]:

\[([^\]\s]+).([^\]]+)\]

参见 regex demo

JS 将 [^] 解析为 *any character including a newline in your regex, and the final character class ] symbol as a literal ].

在这方面,JS 正则表达式引擎偏离了 POSIX standard 其中,智能放置 用于将 [] 符号与括号中的表达式相匹配,例如 [^][].

The ] character is treated as a literal character if it is the first character after ^: [^]abc].

JS and Ruby ,那不是那样工作的:

You can include an unescaped closing bracket by placing it right after the opening bracket, or right after the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. This does not work in JavaScript, which treats [] as an empty character class that always fails to match, and [^] as a negated empty character class that matches any single character. Ruby treats empty character classes as an error. So both JavaScript and Ruby require closing brackets to be escaped with a backslash to include them as literals in a character class.

相关:

关于javascript - PHP 正则表达式和 javascript 正则表达式有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34134741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com