regexboost

How to ignore keywords in regex before variables?


I trying to create a function which is capable of

So it converts

const float x;

to

lowp const float x;

However I would like to ignore the following scenarios:

Based on my previous question link,This is my regex:

  (\bhighp((?:\s+\w+)*)(float|(?:i|b)?vec[2-4]|mat[2-4](?:x[2-4])?)(*SKIP)(?!)|\bfloat\b)

So, I just would like to ignore those cases, when there is a highp|lowp|mediump before float.

I have this regex command:

#include <iostream>
#include <string>
#include <boost/regex/v5/regex.hpp>

using namespace boost;

std::string precisionModulation(std::string& shaderSource) {

    const regex highpFloatRegex2(R"(highp|lowp|mediump((?:\s+\w+)*)(float)(*SKIP)(?!)|(?=\s+(float)))");
    shaderSource = regex_replace(shaderSource, highpFloatRegex2, "lowp");

    return shaderSource;
}

int main() {
    std::string shaderSource = R"(
float foo1;
highp const float foo1;
precision highp float foo2;
    )";

    std::cout << "Original Shader Source:\n" << shaderSource << std::endl;
    std::string modifiedSource = precisionModulation(shaderSource);
    std::cout << "\nModified Shader Source:\n" << modifiedSource << std::endl;

    return 0;
}

Unfortunately I got weird results:

Original Shader Source:

float foo1;
highp const float foo1;
const highp float foo1;
precision highp float foo2;


Modified Shader Source:

lowp float foo1;
highp const lowp float foo1;
const highp lowp float foo1;
precision highp lowp float foo2;

I also tried:

\w*(?<!highp)((?:\s+\w+)*)\s+float

Solution

  • I suggest using

    \bhighp(?:\s+\w+)*\s+(?:float|[ib]?vec[2-4]|mat[2-4](?:x[2-4])?)(*SKIP)(?!)|\b(?:const\s+)?float\b
    

    See the regex demo.

    Details:

    In your code, it should look like

    const regex highpFloatRegex2(R"(\bhighp(?:\s+\w+)*\s+(?:float|[ib]?vec[2-4]|mat[2-4](?:x[2-4])?)(*SKIP)(?!)|\b(?:const\s+)?float\b)");
    shaderSource = regex_replace(shaderSource, highpFloatRegex2, "lowp $0");
    

    Note that the $0 in the replacement pattern stands for the whole match value.