fix(cleaners): anchor the whole pattern in clean_prefix and clean_postfix

SA
9h ago
+34-2

Summary

clean_prefix and clean_postfix interpolate the caller's pattern straight into ^{pattern} and {pattern}$. For a pattern with an alternation, the anchor only binds one branch (^Hi|World is "Hi at the start, or World anywhere"):

>>> clean_prefix("Hello World", "Hi|World")
'Hello '          # World removed from the middle
>>> clean_postfix("Hi there", "Hi|World")
'there'           # Hi removed from the start

The docstrings say the pattern "can be a simple string or a regex pattern", and the same applies through clean(prefix=..., postfix=...). The existing tests only use a parenthesised alternation ((END|STOP)), which is why this went unnoticed.

The fix wraps the pattern in a non-capturing group (^(?:...) / (?:...)$), so the anchor applies to every branch. Patterns that already parenthesise their alternation behave exactly as before.

Validation

  • Added test_clean_prefix_anchors_every_alternative and test_clean_postfix_anchors_every_alternative; 5 of their cases fail without the fix.
  • pytest test_unstructured/cleaners/test_core.py: 172 passed.
  • ruff check and ruff format --check clean on the two touched files.

Release note

clean_prefix / clean_postfix no longer remove a match from the wrong end of the text when the pattern contains an unparenthesised |.

AI-assisted change. I reviewed the diff and ran the tests locally. I can't apply labels; this is a bug fix.