代码之家  ›  专栏  ›  技术社区  ›  gator

如何使用基于C++ 03约束和没有外部库的正则表达式进行字符串操作?

  •  0
  • gator  · 技术社区  · 6 年前

    我有一些字符串,需要对其进行操作,使其小写,并使用regex将一些字符替换为空白。

    Java等价物是:

    str.toLowerCase();
    str.replaceAll("[^a-z]", "");
    str.replaceAll("\\s", "");
    

    c++03 在不使用Boost或其他库的情况下,如何在C++中实现相同的功能?我运行的服务器的g++版本是 4.8.5 20150623 是的。

    小写很简单:

    char asciiToLower(char c) {
        if (c <= 'Z' && c >= 'A') {
            return c - ('A' - 'a');
        }
        return c;
    }
    
    std::string manipulate(std::string str) {
        for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
            it = asciiToLower(it);
        }
    }
    

    但另外两个呢?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Lightness Races in Orbit    6 年前

    C++ 03不支持正则表达式。这是在C++ 11中介绍的。

    所以,如果没有(a)外部库,或者(b)自己编写regex引擎, 你不能 .

    但是,在实验中,gcc从4.9开始支持regex。 -std=c++0x 模式。所以,如果你能换个话题,你的gcc已经足够新了,也许这能帮到你。

    (不要误以为GCC4.8支持: it doesn't; it's lying (第三章)

    否则我建议你更新你的编译器。即使C++ 11现在也是旧的。