javascript - 正则表达式 [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();
}
解决方案
我发现了两种不同的方法,但使用相同的概念:
- 选项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 表达式。我希望你觉得这对你有帮助。
推荐阅读
- python - 我在哪里可以找到 REST API 中的 ELK 版本?
- python - python通过比较语音(语音)进行人工身份验证
- r - ggplot2:对同一组的不同系列使用不同的线型
- c++ - 提供 C++ Singleton 类库但在库外提供 instance() 方法是否可以接受
- intellij-idea - 以 IntelliJ GUI 形式添加动作侦听器时的空指针
- gradient - 如何在没有优化器的情况下将梯度设置为零?
- php - 如何在使用活动记录的框架中实现模型工厂?
- mysql - 在 aws 上使用 lambda 将 json api 数据插入 mysql rds
- laravel - Laravel - 在模型构造函数上重定向
- sql-server - OData 源预览错误:列填充权重之和不能超过 65535