Python 3 正则替换:如何在句末插入空格且保留原有字符?
Ah, I see the issue here—your current regex is matching the lowercase letter before the dot, the dot itself, and the uppercase letter after all as a single sequence. When you replace that match with ". ", you're throwing away those surrounding letters, which is why "mat.The" turns into "ma he".
To fix this, we need to keep those characters while inserting the space between the dot and the uppercase letter. Here are two reliable ways to do it:
Method 1: Capture and Reuse Surrounding Characters
Wrap the lowercase and uppercase letters in parentheses to create capture groups. Then reference those groups in your replacement string to keep them intact:
import re s = 'The cat sat on the mat.The dog sat on the log.' # Capture lowercase before dot, dot, uppercase after dot pattern = r'([a-z])\.([A-Z])' # Replace with: lowercase + ". " + uppercase s = re.sub(pattern, r'\1. \2', s) print(s)
Output:'The cat sat on the mat. The dog sat on the log.'
Breakdown:
([a-z]): Captures the lowercase letter before the dot into group 1\.: Escaped dot (since.is a special regex character that matches any character)([A-Z]): Captures the uppercase letter after the dot into group 2\1. \2: Puts group 1, then the dot with a space, then group 2 back together.
Method 2: Use Lookaround Assertions (Cleaner Approach)
Lookarounds let you check for nearby characters without including them in the match. This means you only match the dot itself (when it's between a lowercase and uppercase letter) and replace it with ". ":
import re s = 'The cat sat on the mat.The dog sat on the log.' # Match dot only if preceded by lowercase and followed by uppercase pattern = r'(?<=[a-z])\.(?=[A-Z])' s = re.sub(pattern, r'. ', s) print(s)
Output:'The cat sat on the mat. The dog sat on the log.'
Breakdown:
(?<=[a-z]): Positive lookbehind—checks that a lowercase letter comes right before the dot (but doesn't include it in the match)\.: Matches the dot(?=[A-Z]): Positive lookahead—checks that an uppercase letter comes right after the dot (also not included in the match)- Replacing just the dot with ". " inserts the space while leaving the surrounding letters untouched.
Both methods work great, but lookarounds are simpler here since you don't have to manage capture groups. Just remember to use raw strings (r'') for your regex patterns in Python to avoid unexpected escaping issues.
内容的提问来源于stack exchange,提问作者SarahJessica

