Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ STL, how do I remove non-numeric characters from std::string with regex_replace?

Using the C++ Standard Template Library function regex_replace(), how do I remove non-numeric characters from a std::string and return a std::string?

This question is not a duplicate of question 747735 because that question requests how to use TR1/regex, and I'm requesting how to use standard STL regex, and because the answer given is merely some very complex documentation links. The C++ regex documentation is extremely hard to understand and poorly documented, in my opinion, so even if a question pointed out the standard C++ regex_replace documentation, it still wouldn't be very useful to new coders.

like image 259
Volomike Avatar asked Sep 20 '25 23:09

Volomike


2 Answers

// 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

Note that the R"..." part means raw string literal and does not evaluate escape codes like a C or C++ string would. This is very important when doing regular expressions and makes your life easier.

Here's a handy list of single-character regular expression raw literal strings for your std::regex() to use for replacement scenarios:

  • R"([^A-Za-z0-9])" or R"([^A-Za-z\d])" = select non-alphabetic and non-numeric
  • R"([A-Za-z0-9])" or R"([A-Za-z\d])" = select alphanumeric
  • R"([0-9])" or R"([\d])" = select numeric
  • R"([^0-9])" or R"([^\d])" or R"([\D])" = select non-numeric
like image 179
Volomike Avatar answered Sep 22 '25 14:09

Volomike


Regular expressions are overkill here.

#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;
}
like image 21
Pete Becker Avatar answered Sep 22 '25 13:09

Pete Becker