我想在input_string
语句中将regex_match
传递到if
之前先左右修剪" 0 "
,但我不确定boost trim_right
and trim_left
尝试是否成功不过如何解决。
如何简单地修剪输入,以使前两个输入" 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.
Route::resource('reports/{id}', 'ReportController');
答案 0 :(得分:1)
最大的问题是std::regex_match
需要一个持久的字符串对象来引用结果。如果没有,那么在检查结果之后,将访问不存在的字符串,这是未定义的行为。这意味着您需要修改循环以使用What's the best way to trim std::string?中的trim_copy
,例如
for (const auto &input_string: string_vector) {
auto trimmed = trim_copy(input_string);
if (std::regex_match(trimmed, expression_two))
cout << "[0-9] Char Class: '" << input_string << "' is a valid number." << endl;
}
这将使您花费一个副本,但这是不修改源数据的唯一方法。如果可以修改源数据,则可以使用
for (auto &input_string: string_vector) {
if (std::regex_match(trim(input_string), expression_two))
cout << "[0-9] Char Class: '" << input_string << "' is a valid number." << endl;
}
相反。