39

I'm just a noob when it comes to regexp. I know Perl is amazing with regexp and I don't know much Perl. Recently started learning JavaScript and came across regex for validating user inputs... haven't used them much.

How does JavaScript regexp compare with Perl regexp? Similarities and differences?
Can all regexp(s) written in JS be used in Perl and vice-versa?
Similar syntax?

Braiam
  • 1
  • 11
  • 47
  • 78
Amitd
  • 4,769
  • 8
  • 56
  • 82
  • 1
    I'm curious to see if anyone answers this. I know the basic regex feature are the same between Perl and JavaScript (^ anchors left, $ anchors right, \b for word boundary, etc). Some of the advanced feature may differ though, like non-greedy matching and back references. – jpsimons Oct 16 '10 at 17:56

4 Answers4

31

From ECMAScript 2018 onwards, many of JavaScript's regex deficiencies have been fixed.

What is still missing:

  • JavaScript doesn't have a way to prevent backtracking by making matches final (using possessive quantifiers ++/*+/?+ or atomic groups (?>...)).
  • Recursive/balanced subgroup matching is not supported.
  • One other (cosmetic) thing is that JavaScript doesn't know verbose regexes, which might make them harder to read.

Other than that, the basic regex syntax is very similar in both flavors.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 3
    You can fake verbose regexs with string concatenation. It's not as nice as true verbose regexes, so the barrier is higher for when you would do it, but it's still an option and is definitely worthwhile in some situations. – Aaron Maenpaa Feb 06 '13 at 14:54
  • Lookbehind assertions have been added in ECMAScript 2018. – Jakob Mar 05 '18 at 20:11
8

This comparison will answer all your queries.

Chris Povirk
  • 3,738
  • 3
  • 29
  • 47
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 5
    Except it's about three years out of date, since it only covers Perl 5.8, and several of the things on that list were added in 5.10. – hobbs Oct 16 '10 at 17:55
  • 1
    @hobbs - some of us still live in the 5.8 world :) – DVK Oct 16 '10 at 18:00
  • 5
    To be specific (that is, actually helpful), 5.10 adds named captures, named backreferences, and the "possessive quantifiers" using `+`, as well as some other stuff related to backtracking control and recursive-descent parsing that isn't in that comparison. – hobbs Oct 16 '10 at 18:31
  • 1
    I cannot see any reference to either Ecmascript or javascript. – EnzoR Sep 29 '17 at 15:03
6

Another difference: In JavaScript, there is no s modifier: The dot "." will never match a newline character. As a replacement for ".", the character class [\s\S] can be used in JavaScript, which will work like /./s in Perl.

rplantiko
  • 2,698
  • 1
  • 22
  • 21
0

I just ran into an instance where the \d, decimal is not recognized in some versions of JavaScript -- you have to use [0-9].

Bob Ray
  • 1,105
  • 10
  • 20