Replace only standalone TODO markers

Replacing every occurrence of TODO can alter text that merely contains those four letters. This example compiles r"\bTODO\b", then replaces only matches bounded by the regular-expression engine’s word-boundary rule. It changes the leading TODO and the parenthesized TODO to DONE. It leaves preTODOpost unchanged because letters on both sides make the embedded text part of one word. It also leaves TODO_1 unchanged because underscore and digits are word characters.

Pattern.subn() returns a pair containing the changed string and the number of replacements. The assertion checks both the complete output and the count of two before printing. That makes the sample’s intended matching behavior explicit, rather than deriving a count from displayed text. Python documents re.Pattern.subn() and \b word boundaries. These are established re APIs; the example requires Python 3 but no newer Python-version feature.

A word boundary follows the regex engine’s definition of word characters. For str patterns, that is Unicode-aware unless ASCII mode is selected. This may differ from a project’s token rules, particularly around hyphens, non-Latin letters, or comment syntax. The assertion demonstrates only these four contexts; it does not establish that a source file has been transformed correctly. For language-aware edits, parse the language when a suitable parser is available.

AI-assistance disclosure: this article was drafted with AI assistance and checked using a synthetic example.

import re

marker = re.compile(r"\bTODO\b")
text = "TODO: polish; preTODOpost stays; TODO_1 stays; (TODO) goes."

updated, count = marker.subn("DONE", text)
assert (updated, count) == (
    "DONE: polish; preTODOpost stays; TODO_1 stays; (DONE) goes.",
    2,
)

print(updated)
DONE: polish; preTODOpost stays; TODO_1 stays; (DONE) goes.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic