14

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

4
  • 4
    have a look at the explanation - see how it differs, regex's are slightly different in different languages - make adjustments as required Commented Aug 16, 2015 at 0:56
  • Are you sure that you want to match something like: @[]User Name])1234). It seems like an odd rule for any practical purpose. Commented Aug 16, 2015 at 18:23
  • @eBusiness - It's actually trying to match something along the lines of @[User Name](1234). It is for a tagging system I have created so that I can convert that into a link to a users profile based on their ID by displaying their username. Commented Aug 18, 2015 at 2:29
  • @Fizzix I kind of figured that, it is just that the . and the second ) doesn't really make any sense in that context. Commented Aug 18, 2015 at 5:53

1 Answer 1

30

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ohhhh, makes much more sense now. Thanks vihan, appreciate it.
Is [\]] different from just \]?
@immibis No. This regex is probably better written as @\[(.[^\]]+)\][()](\d+)\).
Thanks @Blackhole, looks a lot better. I'll run with that instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.