Regexp to find caret preceding integers not working

Question:

I’m trying to replace this [^19) Jones, Owen. with this [^19] Jones, Owen. using this regexp statement:

re.sub(r'(?<=[^[0-9])() )','] ', text)

But no replacement occurs and I’m unable to find the issue. Please help.

Asked By: sheharbano

||

Answers:

You need to use

re.sub(r'([^d+)) ', r'1] ', text)

See the regex demo.

Details:

  • ([^d+) – Group 1 (whose value is referred to with 1 from the replacement pattern): [^ and one or more digits
  • ) – a ) string.

Note you cannot use a lookbehind here, since d+ matches a non-fixed amount of digits, and Python re lookbehind requires fixed-width patterns.

Answered By: Wiktor Stribiżew
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.