You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Copy file name to clipboardExpand all lines: 9-regular-expressions/15-regexp-catastrophic-backtracking/article.md
+2-2
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Catastrophic backtracking
2
2
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.
4
4
5
5
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.
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.
284
284
285
285
```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.
287
287
```
288
288
289
289
Let's rewrite the first example using lookahead to prevent backtracking:
0 commit comments