Skip to content

🐛 FIX: Escape regex characters correctly in utils.escapeRE - #499

Open
kevincommits wants to merge 1 commit into
executablebooks:masterfrom
kevincommits:fix/escape-re-replacement
Open

kevincommits wants to merge 1 commit into
executablebooks:masterfrom
kevincommits:fix/escape-re-replacement

Conversation

@kevincommits

Copy link
Copy Markdown

escapeRE in markdown_it/common/utils.py, exposed to plugins as md.utils.escapeRE, returns a broken pattern for any input that contains a regex special character.

from markdown_it import MarkdownIt
MarkdownIt().utils.escapeRE("a.b*c")

Actual: a\$&b\$&c
Expected: a\.b\*c, which is what markdown-it returns for md.utils.escapeRE('a.b*c') (checked with 14.1.0 and 15.0.1).

The replacement string "\\$&" came over from the JavaScript str.replace(..., '\\$&'), where $& means the whole match. Python's re.sub has no $&, so each special character was replaced with the literal text \$&. The fix uses r"\\\g<0>", the Python spelling of the same replacement. Nothing inside markdown-it-py calls this helper, so parsing output does not change.

The new test in tests/test_port/test_misc.py checks the escaped string and that it compiles to a pattern matching the original text. It fails on master and passes with the fix.

Ran:

  • pytest tests/ (1191 passed)
  • pre-commit run --files markdown_it/common/utils.py tests/test_port/test_misc.py (ruff, ruff-format, mypy passed)
  • Compared the output for every escaped character with markdown-it 14.1.0 and 15.0.1 under Node; all match.

Not run: the mdit-py-plugins job, the benchmark job, and other Python versions (tested on 3.12 only).

The replacement string was copied from JavaScript, where "\\$&" inserts a
backslash and the matched character. Python's re.sub does not support "$&",
so every special character was replaced with the literal text "\$&".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant