如何用正则表达式整理无格式段落?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 😊
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.
You don't even need to leave Sublime to do this! Here are three ways:
方法1:快速正则替换(一键操作,无需配置)
- Open your file and press
Ctrl+H(Windows/Linux) orCmd+H(Mac) to open the Replace panel. - Click the
.*button at the bottom left to enable regex mode. - In the "Find" field, paste:
(?<!\n)\n(?!\n) - In the "Replace" field, type a single space (
). - Click "Replace All"—this fixes all internal newlines.
- 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:
- Go to
Preferences > Key Bindings. - 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 } ] } }
- 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:
- Go to
Tools > Developer > New Plugin. - 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)
- Save it as
clean_paragraphs.pyin your SublimePackages/Userfolder. - 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

