简体   繁体   English

为什么我的正则表达式在PHP中工作而不是JavaScript?

[英]Why does my regular expression work in PHP but not JavaScript?

I have a regex created by myself that I am currently running in PHP. 我有自己创建的正则表达式,我目前正在使用PHP运行。 Although when I merge it over to JavaScript, it refuses to work. 虽然当我将它合并到JavaScript时,它拒绝工作。 I have also tried it in Python and it works perfectly fine. 我也用Python试过它,它的工作原理非常好。

Regex: 正则表达式:

@[[](.[^]]+)[]][()](\d+)[)]

Testing in PHP, and working 在PHP中测试,并正在工作

Testing in JavaScript, and not working 在JavaScript中测试,而不是工作

JavaScript doesn't automatically escape your ] . JavaScript不会自动转义你的]

This will help you get a visual idea: 这将有助于您获得视觉概念:

PCRE: PCRE:

PCRE

JS: JS:

JS

Python: 蟒蛇:

蟒蛇

So to fix this, you need to escape the brackets 所以要解决这个问题,你需要转义括号

@[[](.[^\]]+)[\]][()](\d+)[)]
//      ^     ^  

The best way to write this regex is to minimize the use of character classes: 编写此正则表达式的最佳方法是最小化字符类的使用:

@\[(.[^\]]+)\][()](\d+)\)

That's why it's good practice to escape this stuff instead of relying on quirks of the flavor. 这就是为什么逃避这些东西而不是依赖于味道的怪癖是一个好习惯。

I generated these images through regex101 . 我通过regex101生成了这些图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM