首页 > 解决方案 > 正则表达式 [REGEX] - 替换/替换 - 捕获组 1 和 2 中的内容

问题描述

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

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

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

输入

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();
}

标签: javascriptvisual-studio-codevisual-studio-2017sublimetext3regexp-replace

解决方案


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


  • 选项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\(\);

SUBSTITUTION ~ REPLACE 在任何文本编辑器中

_$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,不仅可以生成 REGEX,还可以为您可能需要的每种编程语言自动生成代码结构。在这里,我发布了一个 JavaScript 示例。在此网页中,您还可以了解如何使用“快速参考”框生成更复杂的 REGEX 表达式。我希望你觉得这对你有帮助。


推荐阅读