Search code examples
javascriptvisual-studio-codevisual-studio-2017sublimetext3regexp-replace

Regular expression [REGEX] - substitution / replace - Contents in capture group 1 & 2


The following task can be generated with something like a regular expression?

The idea is to copy some letters of the method's name into the method code. In the example that I propose, I want to copy the letters that are between "_" from the external method into the internal method.

Having this input, I want to get this output:

INPUT

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

OUTPUT

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

Solution

  • I've discovered two different ways, but using the same concept:


    • Option 1

    For simple substitutions we can use any text editor (like Visual Studio Code, Sublime Text 3, VS2017 code editor...).

    REGULAR EXPRESSION ~ FIND in any text editor

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

    SUBSTITUTION ~ REPLACE in any text editor

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


    • Option 2

    The second option is creating a script with more complex structures in languages like: 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);
    
    

    TIP: You can use some really useful tools like https://regex101.com/r/aAvhEF/1 not only in order to generate your REGEX, you can also generate the code structure automatically for each programming language you could need. Here I've posted an example in JavaScript. In this web page you can also learn how to generate more complex REGEX expressions using the "Quick Reference" box. I hope you find it helpful.