I am trying to insert space ' ' after the colon ':' , if it is missing.
I am matching Full Name:J
capturing group Full Name:
replacing with '\1 '
But it seems the capturing group is not working properly,
I get this distorted result: Full Name: ohn Doe.
Any suggestions?
Thank you.
import re
# Example input string
input_string = "Full Name:John Doe."
# Use re.sub() to add a space after the colon
pattern = r"(Full Name:)\w"
replacement = r"\1 "
# Perform the substitution
result = re.sub(pattern, replacement, input_string)
# Print the result
print(result)
That looks right. You’re matching the string Full Name:J, capturing Full Name:, and so replacing the matched string (not just the captured string) with Full Name: .
From your description of what you want, it seems like you want to match an optional space, not a word character. That regex would look like:
pattern = r'(Full Name:) ?'
This would match Full Name: and be replaced with Full Name: . Or if there already is a space, then you will replace Full Name: with Full Name: .
Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.