Skip to content

Regexes with Quardratic Time on Adversarial Inputs #14020

Open

Description

@Fazel94

How to reproduce the behaviour

HTTP Regex

import time
import spacy

nlp = spacy.blank("en")

for n in (1000, 2000, 4000, 8000, 16000):
    text = "a:" * n
    start = time.perf_counter()
    nlp(text)
    print(f"{len(text):>6} chars  {time.perf_counter() - start:7.2f}s")

would ouput

  2000 chars     0.03s
  4000 chars     0.08s
  8000 chars     0.36s
 16000 chars     1.20s
 32000 chars     4.76s

It is addressed in #14016

NER Format Autodetection

It is addressed in #14017

In spacy/cli/convert.py:213-214 r"\S+\|(O|[IB]-\S+)" and r"\S+\s+(O|[IB]-\S+)$" can lead to quardratic time on some inputs:

import re
import time

line = "x|" * 10000

for name, pattern in [
    ("old", r"\S+\|(O|[IB]-\S+)"),
    ("new", r"\S\|(O|[IB]-\S+)"),
]:
    start = time.perf_counter()
    re.search(pattern, line)
    print(f"{name}: {time.perf_counter() - start:.3f}s")

Would output:

old: 3.523s
new: 0.001s

Also:

import re
import time

line = "a" * 20000

for name, pattern in [
   ("old", r"\S+\s+(O|[IB]-\S+)$"),
   ("new", r"\S\s+(O|[IB]-\S+)$"),
]:
   start = time.perf_counter()
   re.search(pattern, line)
   print(f"{name}: {time.perf_counter() - start:.3f}s")

Would output:

old: 4.900s
new: 0.001s

Your Environment

  • Operating System: Ubuntu 24.04
  • Python Version Used: 3.12.1
  • spaCy Version Used: 3.8.0

Activity

  1. Fazel94 commented on Aug 21, 2026

    @Fazel94
    Author

    In affix regexes of languages el and pt there is still some more quadratic regexes.

    import re
    import time
    
    el_infix = re.compile(r"([a-zA-Z]+)\/([a-zA-Z]+)\/([a-zA-Z]+)")
    pt_infix = re.compile(r"(\w+-\w+(-\w+)*)")
    
    for name, pattern in [("el", el_infix), ("pt", pt_infix)]:
        print(name)
        for n in (5_000, 10_000, 20_000, 40_000):
            text = "a" * n  # no "/" or "-" -> never matches
            start = time.perf_counter()
            list(pattern.finditer(text))
            elapsed = time.perf_counter() - start
            print(f"  n={n:>6}  {elapsed:6.2f}s")

    Output:

    el
      n=  5000    0.24s
      n= 10000    1.03s
      n= 20000    4.09s
      n= 40000   17.11s
    pt
      n=  5000    0.11s
      n= 10000    0.39s
      n= 20000    1.54s
      n= 40000    7.95s
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions