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.
// 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-numericR"([A-Za-z0-9])"
or R"([A-Za-z\d])"
= select alphanumericR"([0-9])"
or R"([\d])"
= select numericR"([^0-9])"
or R"([^\d])"
or R"([\D])"
= select non-numericRegular 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With