我在正则表达式中工作,我的正则表达式是 /\[([^]\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 anx
.[^]x]
matches any character that is not a closing bracket or anx
. 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.
相关:
(?1)
regex subroutine用于缩短 PCRE 模式转换 - REGEX from PHP to JS
关于javascript - PHP 正则表达式和 javascript 正则表达式有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34134741/