如何忽略正则表达式中变量之前的关键字?

问题描述 投票:0回答:1

我试图创建一个能够实现的功能

  • 将精度调制器关键字放在浮点变量前面,其中 没有这个关键字

所以它转换了

const float x;

lowp const float x;

但是我想忽略以下场景:

  • 当已经有精度修饰符时:
    lowp const float x;
  • 当有默认精度调制器时:
    precision lowp float;

根据我之前的问题链接,这是我的正则表达式:

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

所以,当浮动之前有 highp|lowp|mediump 时,我只想忽略这些情况。

我有这个正则表达式命令:

#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;
}

不幸的是我得到了奇怪的结果:

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;

我也尝试过:

\w*(?<!highp)((?:\s+\w+)*)\s+float
regex boost
1个回答
0
投票

我建议使用

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

请参阅 正则表达式演示

在你的代码中,它应该看起来像

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");

请注意,替换模式中的

$0
代表整个匹配值。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.