Notepad++正则表达式替换:保留指定字符合并特定方括号内容
Got it, let's figure out how to solve this targeted regex replacement in Notepad++. The key here is we only want to merge the second bracket into the first only when the line starts with * BATCH *—leaving all other ] [ pairs untouched. Here's exactly what to do:
Step 1: Open the Replace Dialog
Hit Ctrl+H in Notepad++ to bring up the Find/Replace window—this is where we'll set up our regex.
Step 2: Configure Regex Settings
Before entering patterns, make sure these settings are correct:
- Switch to the Regular expression search mode (select the radio button).
- Uncheck . matches newline (we don't want to match across line breaks here).
- If your
* BATCH *is always uppercase, keep Match case checked to avoid accidental matches on lowercase variants.
Step 3: Enter the Regex Patterns
Find what:
(\* BATCH \* \[[^\]]+) \[([^\]]+)\]
Let me break this down so you know exactly what it's targeting:
(\* BATCH \* \[[^\]]+): This first capture group grabs everything from* BATCH * [up to (but not including) the closing]of the first bracket. The[^\]]+part ensures we only capture text inside that first bracket until we hit its closing].\[([^\]]+)\]: This matches the space, opening[, captures the text inside the second bracket (as our second group), then the closing].
Replace with:
\1 \2]
Here's how this fixes the string:
\1: Inserts the content from our first capture group (the start of the line up to the end of the first bracket's inner text, no closing]).\2: Adds a space followed by the text we pulled from the second bracket.]: Re-adds the closing bracket to complete the merged first bracket.
Step 4: Test and Apply Changes
- First, click Find Next to double-check it's only matching the
] [pairs you want to modify (the ones right after the first bracket in* BATCH *lines). - Once you're confident it's targeting correctly, click Replace All to apply the changes across your entire document.
Example Results
Let's verify with your sample inputs:
- Original:
* BATCH * [Qh 4c 2c] [9h] [9c]
After replacement:* BATCH * [Qh 4c 2c 9h] [9c]✅ - Original:
* BATCH * [Js 8c 3s] [8h] [Th]
After replacement:* BATCH * [Js 8c 3s 8h] [Th]✅
This regex won't touch any ] [ pairs outside of the * BATCH * context, so all your other content will stay exactly as it is.
内容的提问来源于stack exchange,提问作者jmtbdj

