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

标签 javascript php regex

我在正则表达式中工作,我的正则表达式是 /\[([^]\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/

相关文章:

javascript - ReactJS 引用号 : undefined error getting input element value

javascript - HTML5 视频 addEventListener 'ended' 未触发

PhpStorm 和扩展的 php 定义

php - 如何在带有 WHILE 获取行的 MySQL 查询中使用 PHP 变量?

php - 将 CSV 数据导入 MySQL 数据库中的字段

python - Django URL 正则表达式 : make URL tolerate int or float values

正则表达式 - 如何让我的表达式不区分大小写?

regex - 在 JSON Schema 中使用 RegEx

javascript - 如何制作一个功能来显示/隐藏不同的对象?

javascript - 我可以在对象声明中进行数组解构赋值吗?