Skip to content

Commit dad802a

Browse files
authored
Add a solution for catastrophic backtracking that enables the direct use of atomic groups
The solution described where atomic groups are emulated using lookahead and backreferences is useful but can be tricky to use and error prone (e.g. when quantifying the result, or in longer patterns that rely on multiple atomic groups). So this adds a link to an easy to use solution that enables the direct use of atomic groups via `(?>…)` in native JS regexes.
1 parent 2092da7 commit dad802a

File tree

1 file changed

+2
-2
lines changed
  • 9-regular-expressions/15-regexp-catastrophic-backtracking

1 file changed

+2
-2
lines changed

9-regular-expressions/15-regexp-catastrophic-backtracking/article.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Catastrophic backtracking
22

3-
Some regular expressions are looking simple, but can execute a veeeeeery long time, and even "hang" the JavaScript engine.
3+
Some regular expressions look simple, but can execute a veeeeeery long time, and even "hang" the JavaScript engine.
44

55
Sooner or later most developers occasionally face such behavior. The typical symptom -- a regular expression works fine sometimes, but for certain strings it "hangs", consuming 100% of CPU.
66

@@ -283,7 +283,7 @@ alert( "JavaScript".match(/(?=(\w+))\1Script/)); // null
283283
We can put a more complex regular expression into `pattern:(?=(\w+))\1` instead of `pattern:\w`, when we need to forbid backtracking for `pattern:+` after it.
284284

285285
```smart
286-
There's more about the relation between possessive quantifiers and lookahead in articles [Regex: Emulate Atomic Grouping (and Possessive Quantifiers) with LookAhead](https://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead) and [Mimicking Atomic Groups](https://blog.stevenlevithan.com/archives/mimic-atomic-groups).
286+
There's more about the relation between possessive quantifiers and lookahead in articles [Regex: Emulate Atomic Grouping (and Possessive Quantifiers) with LookAhead](https://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead) and [Mimicking Atomic Groups](https://blog.stevenlevithan.com/archives/mimic-atomic-groups). You can also use the [Regex.make](https://github.com/slevithan/regex-make) library which adds support for atomic groups, making this pattern easier to use.
287287
```
288288

289289
Let's rewrite the first example using lookahead to prevent backtracking:

0 commit comments

Comments
 (0)