![](/img/trans.png)
[英]How do I insert format str and don't remove the matched regular expression in input string in boost::regex_replace() in C++?
[英]In C++ STL, how do I remove non-numeric characters from std::string with regex_replace?
使用C ++标准模板库函数regex_replace()
,如何从std::string
删除非数字字符并返回std::string
?
此问题不是问题747735的重复,因为该问题要求如何使用TR1 / regex,并且我要求如何使用标准STL regex,并且给出的答案只是一些非常复杂的文档链接。 在我看来,C ++ regex文档非常难以理解,而且文档编写得很差,因此,即使有问题指出了标准的C ++
regex_replace
文档 ,对于新的编码人员而言,它仍然不是很有用。
// 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
请注意, 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])"
=选择非数字 正则表达式在这里过大了。
#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;
}
对于给定样本的详细信息,可以接受的答案。 但是它将失败,例如“ -12.34”(这将导致“ 1234”)。 (请注意样本可能是负数)
那么正则表达式应该是:
(-|\+)?(\d)+(.(\d)+)*
说明:(可选(“-”或“ +”))与(一个数字,重复1到n次)与(可选的结尾是:(一个“。”后跟(一个数字,重复1到n次))
有点过分了,但是我一直在寻找这个,并且页面首先出现在我的搜索中,所以我添加了我的答案以供将来搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.