如何用Notepad++正则匹配#include行中的>字符并替换
Fix: Replace
> in #include Lines Only (Notepad++) Got it, let's solve this exact problem: we need to swap out any > characters that appear on lines containing #include for a ", without touching other > in your code (like those in template<class Alloc>). We'll use Notepad++'s regex find-and-replace to target only the right lines.
Step-by-Step Instructions
- Open your file in Notepad++, press
Ctrl+Hto open the Find/Replace dialog. - Switch to the Replace tab.
- Check the Regular expression box at the bottom left (make sure
. matches newlineis unchecked). - Choose one of the two regex patterns below based on your needs:
Option 1: Replace the First > on the #include Line (Most Common)
This works for standard #include lines that only have one > (like your example #include "utility>):
- Find what:
^(.*#include.*?)>(.*)$ - Replace with:
\1"\2
How This Regex Works:
^anchors the match to the start of the line(.*#include.*?)captures everything from the start of the line up to the first>(the*?is non-greedy, so it stops at the first>instead of skipping ahead)>targets the exact character we want to replace(.*)$captures everything after the>to the end of the line\1"\2puts it all back together: the first captured section, a"instead of>, then the rest of the line.
Option 2: Replace All > on the #include Line
If you have a rare case where a single #include line has multiple > characters (e.g., #include "file>with>extra>chars>), use this to replace every > on that line:
- Find what:
(?<=.*#include.*)> - Replace with:
"
How This Regex Works:
(?<=.*#include.*)is a positive lookbehind—it checks that the>is on a line that contains#include(anywhere before the>)>targets the character to replace- Since this doesn't capture the whole line, every matching
>on a #include line gets swapped for".
Example Results
- Original line:
#include "utility>→ Becomes#include "utility" - Unchanged line:
template<class Alloc>→ Stays exactly as is - Commented #include line:
// #include "broken>→ Becomes// #include "broken"
Notes
- This preserves all comments and existing content on the line—only the
>gets swapped. - If your #include lines have leading whitespace (e.g., indentation), the regex will still catch them, since
.*matches any characters (including spaces) before#include.
内容的提问来源于stack exchange,提问作者Cam Krout
相关产品推荐
相关产品推荐

