Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Although when I merge it over to JavaScript, it refuses to work. I have also tried it in Python and it works perfectly fine.

Regex:

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

Testing in PHP, and working

Testing in JavaScript, and not working

like image 345
Fizzix Avatar asked Aug 16 '15 00:08

Fizzix


People also ask

Does regex work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.

Is Java regex different from JavaScript?

There is a difference between Java and JavaScript regex flavors: JS does not support lookbehind. A tabulation of differences between regex flavors can be found on Wikipedia. However, this does not apply to your case.

Does PHP support regex?

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

What is regex in JavaScript?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .


Video Answer


1 Answers

JavaScript doesn't automatically escape your ].

This will help you get a visual idea:

PCRE:

PCRE

JS:

JS

Python:

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.

like image 191
Downgoat Avatar answered Oct 07 '22 00:10

Downgoat