如何跨行重排正则分组?附示例及尝试方案
Let's fix that regex issue for you! The problem with your original pattern was that you mixed up the grouping order and didn't properly handle the line break between the page number and subtitle.
Correct Regex Pattern (for cross-line rearrangement)
First, let's break down the input structure you're dealing with:
- Line 1:
[Number. Main Title]/[Page Number] - Line 2:
Subtitle
We need to capture these key components in the right order:
- Number + Main Title
- Page number segment (
/XXX) - Line break + any whitespace between the two lines
- Subtitle
Find Regex (enable multi-line mode in your editor if available):
(\d+\. .*?)(\/\d+)\s*\r?\n(.*)
(\d+\. .*?): Captures the number (e.g.,14.) and main title (e.g.,SEPARATION ANXIETY) using non-greedy matching to stop exactly at the/(\/\d+): Captures the full page number segment (e.g.,/265)\s*\r?\n: Matches any leading whitespace before the line break, plus the line break itself (works for both Windows\r\nand Unix\nline endings)(.*): Captures the full subtitle text
Replace With:
$1 – $3$2
$1: Inserts the number + main title–: Adds the em dash separator$3: Inserts the subtitle$2: Appends the page number segment at the end
Example Test
Input:
14. SEPARATION ANXIETY/265 The Continuing Saga of Zero-Gravity Elimination
Output after replacement:
14. SEPARATION ANXIETY – The Continuing Saga of Zero-Gravity Elimination/265
For Single-Line Input
If your content is actually a single line (e.g., 14. SEPARATION ANXIETY/265 The Continuing Saga of Zero-Gravity Elimination), use this simplified version:
Find Regex:
(\d+\. .*?)(\/\d+)( .*)
Replace With:
$1 – $3$2
This works by capturing the main title, page segment, and subtitle in sequence, then rearranging them to your desired format.
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

