Why is there no Lookbehind in Javascript?

Asked

Viewed 222 times

7

I hear there’s no such thing as group Construct lookbehind in Regex’s made in Javascript then I appeared some doubts as:

  • Because there is no?
    Is there any reason that makes it incompatible c/the language or unnecessary?
  • If unnecessary, there is an alternative to using lookbehind that causes the same result?
  • Because only that language doesn’t have that group Construct?

1 answer

5


Updating

Lookbehind was accepted in specification of Ecmascript in 2018. So far it has been implemented only in V8. So if you’re a developer of Chrome-only environments (like Electron), or Node, you can already use this assertion, avoid if your application is multi browser, following a list of platforms that accept Lookbehind.

Supported platforms:

Use of Positive lookbehind:

console.log(
  "$9.99  €8.47".match(/(?<=\$)\d+(\.\d*)?/) // Encontra "9.99"
);

Use of Negative lookbehind:

console.log(
  "$9.99  €8.47".match(/(?<!\$)\d+(?:\.\d*)/) // Encontra "8.47"
);


OLD

After some time studying the subject I arrived at the following conclusions:

Because there is no (negative/positive lookbehind)?

It seems that Brendan Eich did not know of its existence at the time, because Netscape was made in an old version of Perl.

Even so, some implementation attempts were made after some time, but without success due to the complexity of implementation, because the Regular Expressions in Ecmascript work from backtracking, which is also necessary for the use of lookbehind, so if the use of lookbehind were incorrect it could lead to some problems such as catastrophic backtracking.


Is there any reason that makes it incompatible c/the language or unnecessary?

It is not incompatible or impossible to implement, but there has not yet been presented a way of implementation that is performative, however there is a proposal that is already in stage 3 of implementation for the use of lookbehind is compatible with Ecmascript.

I wouldn’t say unnecessary, because there is a gain in performance when using group Construct Lookahead or lookbehind


[...] there is some alternative to using lookbehind that causes the same result?

If we don’t take performance into account, you can get the same results using multiple capture groups or even Lookahead’s in the same expression.
As you can see in this example.


Because only this language does not have this group Construct?

As already mentioned, it is really difficult to do something performative and that presents a stable behavior when used with others tokens and group constructs, however as it is already in stage 3 its implementation in Ecmascript, I believe that this will not be true for long.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.