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

How do I perform regex based string manipulation with a C++03 constraint and no external libraries?

我有一些字符串需要将其处理为小写并使用正则表达式将一些字符替换为空白。

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

但是另外两个呢?

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

所以,如果没有 (a) 外部库,或 (b) 自己编写正则表达式引擎,你不能

但是,从 4.9 开始,GCC 在实验性 -std=c++0x 模式下支持正则表达式。所以,如果你能做到这一点,并且你的 GCC 足够新,也许这可以帮助你。

(不要误以为GCC 4.8支持:it doesn't; it's lying。)

否则我建议你更新你的编译器。甚至 C++11 现在也很旧了。