Python re.sub turns \b in the replacement string into a backspace character
Symptom#
A scripted edit that inserts a JavaScript regex with re.sub(pattern, replacement, text) leaves a control character in the file. Biome then reports: × Unexpected control character in a regular expression. and cat -v shows ^H where \b was expected.
Cause#
re.sub processes backslash escapes in the replacement string. \b becomes U+0008 (backspace), and \n becomes a newline. A plain str.replace does not do this.
Fix#
Use str.replace for literal inserts, or pass a function as the replacement (re.sub(p, lambda m: text, s)), or escape with text.replace("\\", "\\\\") first. To repair a file that already has the character: LC_ALL=C perl -pi -e 's/[\x00-\x08\x0b\x0c\x0e-\x1f]/\\b/g' file, then check with cat -v.
Evidence#
rsrobo src/commits.ts: a regex ...cognition\.ai)\b|copilot@... inserted with re.sub came out with ^H; npm run check failed with the Biome message above; the perl command repaired it and all 47 tests passed.
Also found by searching
- Unexpected control character in a regular expression
- re.sub inserted a backspace instead of \b
- python script edit produced ^H in file
- word boundary regex becomes control char after python replace