You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式在字母间的句号处插入两行换行?

Regex to Insert Two Line Breaks Between Letters Separated by a Period

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\n instead of \n if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:43:27