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

如何用正则表达式整理无格式段落?Python或Sublime Text 3实现咨询

Hey there! Let's break this down into two parts: a simpler Python approach, and how to do this directly in Sublime Text 3—perfect for a regex newbie like you 😊

Python 段落整理的简便方法

You don't need overly complex regex to get this done. Here are two straightforward approaches:

方法1:纯字符串操作(新手友好,不用正则)

This method splits your text into paragraphs first, cleans up each paragraph internally, then puts everything back together. No regex required if you prefer:

def clean_paragraphs(text):
    # Split text into paragraphs using empty lines as separators
    paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
    # For each paragraph, replace all newlines/extra spaces with single spaces
    cleaned_paragraphs = [' '.join(p.split()) for p in paragraphs]
    # Join paragraphs back with empty lines
    return '\n\n'.join(cleaned_paragraphs)
  • split('\n\n') breaks the text where there are empty lines (your paragraph separators)
  • ' '.join(p.split()) takes care of all internal newlines and multiple spaces, turning them into single spaces automatically.

方法2:简洁正则方法

If you want to use regex (it's faster for large texts), this pattern targets only the newlines inside paragraphs (not the empty lines between them):

import re

def clean_paragraphs_regex(text):
    # Replace single newlines inside paragraphs with spaces
    # The regex means: "a newline that isn't preceded or followed by another newline"
    cleaned = re.sub(r'(?<!\n)\n(?!\n)', ' ', text)
    # Replace any multiple spaces/tabs with a single space
    cleaned = re.sub(r'\s+', ' ', cleaned)
    return cleaned

The (?<!\n) and (?!\n) are "negative lookbehind/lookahead" assertions—they make sure we only touch newlines that are between actual text, not the ones that separate paragraphs.


在 Sublime Text 3 中实现段落整理

You don't even need to leave Sublime to do this! Here are three ways:

方法1:快速正则替换(一键操作,无需配置)

  1. Open your file and press Ctrl+H (Windows/Linux) or Cmd+H (Mac) to open the Replace panel.
  2. Click the .* button at the bottom left to enable regex mode.
  3. In the "Find" field, paste: (?<!\n)\n(?!\n)
  4. In the "Replace" field, type a single space ( ).
  5. Click "Replace All"—this fixes all internal newlines.
  6. To clean up extra spaces, run another replace: find \s+, replace with (again in regex mode).

方法2:自定义快捷键(一键搞定所有步骤)

If you do this often, bind it to a keyboard shortcut:

  1. Go to Preferences > Key Bindings.
  2. In the right-hand user settings, add this:
{
    "keys": ["ctrl+shift+alt+p"], // Pick any shortcut you like
    "command": "replace",
    "args": {
        "replacements": [
            {
                "find": "(?<!\\n)\\n(?!\\n)",
                "replace": " ",
                "greedy": true,
                "regex": true
            },
            {
                "find": "\\s+",
                "replace": " ",
                "greedy": true,
                "regex": true
            }
        ]
    }
}
  1. Save, and now your shortcut will run both replacements in one go.

方法3:简单自定义插件(for more control)

If you want to add extra logic later, a tiny plugin works:

  1. Go to Tools > Developer > New Plugin.
  2. Replace the default code with this:
import sublime
import sublime_plugin
import re

class CleanParagraphsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # Get selected text (or entire file if nothing's selected)
        region = self.view.sel()[0]
        if region.empty():
            region = sublime.Region(0, self.view.size())
        text = self.view.substr(region)
        
        # Use our regex cleaning logic
        cleaned = re.sub(r'(?<!\n)\n(?!\n)', ' ', text)
        cleaned = re.sub(r'\s+', ' ', cleaned)
        
        # Replace the original text with cleaned version
        self.view.replace(edit, region, cleaned)
  1. Save it as clean_paragraphs.py in your Sublime Packages/User folder.
  2. Add a shortcut for it in Key Bindings:
{
    "keys": ["ctrl+shift+p"],
    "command": "clean_paragraphs"
}

All these methods are beginner-friendly—you don't need to be a regex expert to use them!

内容的提问来源于stack exchange,提问作者rsc05

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:10:33