【问题标题】:Regular expression [REGEX] - substitution / replace - Contents in capture group 1 & 2正则表达式 [REGEX] - 替换/替换 - 捕获组 1 和 2 中的内容
【发布时间】:2020-10-04 07:24:02
【问题描述】:

以下任务可以用正则表达式之类的东西生成吗?

这个想法是将方法名称的一些字母复制到方法代码中。在我提出的示例中,我想将“_”之间的字母从外部方法复制到内部方法中。

有了这个输入,我想得到这个输出:

输入

int mat::CClassA::GetRele_11K11_C_A2_ST() const
{
    bool aux1 = this->GetXXX__YY();
}

int namsp::CClassA::GetRele_45K32_C_B3_ST() const
{
    bool aux1 = this->GetXXX__YY();
}

输出

int mat::CClassA::GetRele_11K11_C_A2_ST() const
{
    bool aux1 = this->GetXXX_11K11_YY();
}

int namsp::CClassA::GetRele_45K32_C_B3_ST() const
{
    bool aux1 = this->GetXXX_45K32_YY();
}

【问题讨论】:

    标签: javascript visual-studio-code visual-studio-2017 sublimetext3 regexp-replace


    【解决方案1】:

    我发现了两种不同的方法,但使用相同的概念:


    • 选项 1

    对于简单替换,我们可以使用任何文本编辑器(如 Visual Studio Code、Sublime Text 3、VS2017 代码编辑器...)。

    正则表达式~在任何文本编辑器中查找

    _(\d\d\w\d\d)_C_(\w\d)_ST\(\) const\n\{\n\tbool aux1 = this->GetXXX__YY\(\);

    替换~在任何文本编辑器中替换

    _$1_C_$2_ST\(\) const\n\{\n\tbool aux1 = this->GetXXX_$1_YY\(\);


    • 选项 2

    第二个选项是使用 Python、PHP、C#、Java ... 等语言创建具有更复杂结构的脚本

    const regex = /_(\d\d\w\d\d)_C_(\w\d)_ST\(\) const\n\{\n\tbool aux1 = this->GetXXX__YY\(\);/gm;
    const str = `int mat::CClassA::GetRele_11K11_C_A2_ST() const
    {
        bool aux1 = this->GetXXX__YY();
    }
    
    int namsp::CClassA::GetRele_45K32_C_B3_ST() const
    {
        bool aux1 = this->GetXXX__YY();
    }`;
    const subst = `_$1_C_$2_ST() const\n\{\n\tbool aux1 = this->GetXXX_$1_YY();`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);
    
    

    提示:您可以使用一些非常有用的工具,例如https://regex101.com/r/aAvhEF/1,不仅可以生成您的正则表达式,还可以为每个编程自动生成代码结构您可能需要的语言。在这里,我发布了一个 JavaScript 示例。在此网页中,您还可以学习如何使用“快速参考”框生成更复杂的 REGEX 表达式。希望对您有所帮助。

    【讨论】:

    • Python 2 已达到其生命周期 (EOL),并且近十年来一直鼓励所有新项目使用 Python 3。确实没有理由让新的独立代码与 Py2 兼容,除非它必须与旧代码库交互,而这不会。
    • 我已将示例更改为尚未达到其 EOL =) 的 JavaScript。谢谢@MattDMo
    猜你喜欢
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2020-10-09
    • 1970-01-01
    • 2014-06-19
    • 2010-11-19
    相关资源
    最近更新 更多