如何使用正则表达式在字母间的句号处插入两行换行?
Got it, let's solve this regex problem! Your goal is to insert two line breaks right after a period that sits directly between two letters (no spaces in between)—exactly skipping cases where there's a space after the period (like your fourth sentence). Here's how to pull this off:
Step 1: The Regex Pattern
We need to target periods that are immediately preceded and followed by a letter (no whitespace in between). Use this lookaround-based regex:
(?<=[a-zA-Z])\.(?=[a-zA-Z])
Breakdown of the pattern:
(?<=[a-zA-Z]): Positive lookbehind — ensures the period comes right after any uppercase or lowercase letter.\.: Escaped period (since.is a special character in regex that matches any character, we need to escape it to match a literal period).(?=[a-zA-Z]): Positive lookahead — ensures the period is immediately followed by any uppercase or lowercase letter.
Step 2: The Replacement String
Replace matches with . followed by two line breaks. Depending on your language, this will be:
- In most languages:
.\n\n(use\r\ninstead of\nif you need Windows-style line endings) - In raw string literals (like Python's
r''):r'.\n\n'
Step 3: Example Usage
Let's test this with your scenario. Suppose your input string is:
Hello.This is a test.It works great.But the fourth sentence has spaces. Like this one.
Running the regex replace will output:
Hello.
This is a test.
It works great.
But the fourth sentence has spaces. Like this one.
Notice how the fourth sentence (with a space after the period) is left untouched—perfect, since the regex only matches periods with no spaces between letters.
Code Examples in Common Languages
Python
import re input_text = "Hello.This is a test.It works great.But the fourth sentence has spaces. Like this one." processed_text = re.sub(r'(?<=[a-zA-Z])\.(?=[a-zA-Z])', r'.\n\n', input_text) print(processed_text)
JavaScript
const inputText = "Hello.This is a test.It works great.But the fourth sentence has spaces. Like this one."; const processedText = inputText.replace(/(?<=[a-zA-Z])\.(?=[a-zA-Z])/g, '.\n\n'); console.log(processedText);
PHP
$inputText = "Hello.This is a test.It works great.But the fourth sentence has spaces. Like this one."; $processedText = preg_replace('/(?<=[a-zA-Z])\.(?=[a-zA-Z])/', ".\n\n", $inputText); echo $processedText;
内容的提问来源于stack exchange,提问作者ElectroMotiveHorse

