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.
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.
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.
You need to use
re.sub(r'([^d+)) ', r'1] ', text)
See the regex demo.
Details:
([^d+)
– Group 1 (whose value is referred to with1
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.