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

如何用PowerShell正则表达式提取完整C++类定义?

问题:PowerShell正则无法完整提取C++类定义

使用PowerShell脚本提取C++类定义时,现有正则表达式(?sm)(class Node_. {[^;]+;)仅能匹配类的部分内容,无法正确识别类结尾的};,导致匹配结果不完整。

原PowerShell脚本:

$source = 
    "class Node_A {               `n" +
    "public:                      `n" +
    "    Node_A();                `n" +
    "    int foo( int a ) {       `n" +
    "        return a * b;        `n" +
    "    }                        `n" +
    "    int b;                   `n" +
    "};                           `n" +
    "                             `n" +
    "class Node_B {               `n" +
    "public:                      `n" +
    "    Node_B();                `n" +
    "    int foo( int a ) {       `n" +
    "        return a + b;        `n" +
    "    }                        `n" +
    "    int b;                   `n" +
    "};                           "

$to_find = "(?sm)(class Node_. {[^;]+;)"
$source |
    select-string $to_find -AllMatches |
    foreach { $_.Matches } |
    foreach { $_.Value }

当前错误匹配结果:

class Node_A {
public:
    Node_A();
class Node_B {
public:
    Node_B();

解决方案

原正则的问题在于[^;]+会在遇到第一个;(比如构造函数行的分号)时就终止匹配,无法处理类内部的嵌套大括号(如成员函数的实现块)和后续的分号。要匹配完整的类定义,需要利用.NET正则的平衡组特性来跟踪嵌套的大括号,确保匹配到外层的};。

修改后的正则表达式

(?sm)(class Node_. {((?>[^{}]+|{(?<depth>)|}(?<-depth>))*(?(depth)(?!))};)

修改后的完整脚本

$source = 
    "class Node_A {               `n" +
    "public:                      `n" +
    "    Node_A();                `n" +
    "    int foo( int a ) {       `n" +
    "        return a * b;        `n" +
    "    }                        `n" +
    "    int b;                   `n" +
    "};                           `n" +
    "                             `n" +
    "class Node_B {               `n" +
    "public:                      `n" +
    "    Node_B();                `n" +
    "    int foo( int a ) {       `n" +
    "        return a + b;        `n" +
    "    }                        `n" +
    "    int b;                   `n" +
    "};                           "

# 修改后的正则表达式
$to_find = "(?sm)(class Node_. {((?>[^{}]+|{(?<depth>)|}(?<-depth>))*(?(depth)(?!))};)"
$source |
    select-string $to_find -AllMatches |
    foreach { $_.Matches } |
    foreach { $_.Value }

正确匹配结果

class Node_A {
public:
    Node_A();
    int foo( int a ) {
        return a * b;
    }
    int b;
};
class Node_B {
public:
    Node_B();
    int foo( int a ) {
        return a + b;
    }
    int b;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:43:24