在 C++ STL 中,如何使用 regex_replace 从 std::string 中删除非数字字符?

Vol*_*ike 1 c++ regex replace stl

使用 C++ 标准模板库函数regex_replace(),如何从 a 中删除非数字字符std::string并返回 a std::string

这个问题不是问题 747735的重复, 因为该问题要求如何使用 TR1/regex,而我要求如何使用标准 STL regex,并且因为给出的答案只是一些非常复杂的文档链接。在我看来,C++ regex 文档非常难以理解并且文档很差,因此即使问题指出了标准 C++ regex_replace 文档,它对新编码人员仍然不是很有用。

Vol*_*ike 6

// assume #include <regex> and <string>
std::string sInput = R"(AA #-0233 338982-FFB /ADR1 2)";
std::string sOutput = std::regex_replace(sInput, std::regex(R"([\D])"), "");
// sOutput now contains only numbers
Run Code Online (Sandbox Code Playgroud)

请注意,该R"..."部分表示原始字符串文字,并且不会像 C 或 C++ 字符串那样评估转义码。这在执行正则表达式时非常重要,可以让您的生活更轻松。

这是一个方便的单字符正则表达式原始文字字符串列表,供您std::regex()用于替换方案:

  • R"([^A-Za-z0-9])"R"([^A-Za-z\d])"= 选择非字母和非数字
  • R"([A-Za-z0-9])"R"([A-Za-z\d])"= 选择字母数字
  • R"([0-9])"R"([\d])"= 选择数字
  • R"([^0-9])"R"([^\d])"R"([\D])"= 选择非数字


Pet*_*ker 5

正则表达式在这里是多余的。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

inline bool not_digit(char ch) {
    return '0' <= ch && ch <= '9';
}

std::string remove_non_digits(const std::string& input) {
    std::string result;
    std::copy_if(input.begin(), input.end(),
        std::back_inserter(result),
        not_digit);
    return result;
}

int main() {
    std::string input = "1a2b3c";
    std::string result = remove_non_digits(input);
    std::cout << "Original: " << input << '\n';
    std::cout << "Filtered: " << result << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)