我想在input_string
语句中将regex_match
传递到if
之前对其进行左右修剪,但我没有尝试过boost trim_right
and trim_left
,但不确定如何解决。
我如何简单地修剪输入,以使前两个输入trim_right
和trim_left
成为有效数字?
" 0 "
" 0.1 "
#include <string>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <regex>
#include <vector>
using namespace std;
int main() {
vector<string> string_vector = {" 0 "," 0.1 ","abc","1 a","2e10","-90e3","1e","e3","6e-1","99e2.5","53.5e93","--6","-+3","95a54e53"};
regex expression_two("^[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*|[0-9]+)[Ee][+-]?[0-9]+$|^[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*|[0-9]+)$|^[+-]?[0-9]+$");
for (const auto &input_string: string_vector) {
if (std::regex_match(input_string, expression_two))
cout << "[0-9] Char Class: '" << input_string << "' is a valid number." << endl;
}
return 0;
}
最大的问题是,[0-9] Char Class: '2e10' is a valid number.
[0-9] Char Class: '-90e3' is a valid number.
[0-9] Char Class: '6e-1' is a valid number.
[0-9] Char Class: '53.5e93' is a valid number.
需要一个持久的字符串对象来引用结果。如果没有,那么在检查结果之后,将访问不存在的字符串,这是未定义的行为。这意味着您需要修改循环以使用[0-9] Char Class: ' 0 ' is a valid number.
[0-9] Char Class: ' 0.1 ' is a valid number.
[0-9] Char Class: '2e10' is a valid number.
[0-9] Char Class: '-90e3' is a valid number.
[0-9] Char Class: '6e-1' is a valid number.
[0-9] Char Class: '53.5e93' is a valid number.
中的std::regex_match
,例如
std::regex_match
这将使您花费一个副本,但这是不修改源数据而执行此操作的唯一方法。如果可以修改源数据,则可以使用
trim_copy
代替。