【发布时间】:2018-06-21 14:45:25
【问题描述】:
我想检查一个十进制数是否符合预定义的标准。我使用了以下正则表达式 ^[+-]?[0-9]+(.[0-9]{2,4})$ ,但它似乎不适用于 C++。我已经尝试了许多正则表达式验证解决方案,它可以按预期工作。例如,如果我有数字 0.00000,则输出应为 false,另一方面,如果数字为 0.00,则输出应为 true。在我的情况下,输出似乎没有检测到任何东西。这是我的源代码,你能帮忙吗?谢谢。
void detectFormatConsistency()
{
std::regex dbl("^[+-]?[0-9]+(\\.[0-9]{2,4})$");
std::smatch matches;
int detected = 0;
for(unsigned int index = 0; index < mixedDistro.size(); index++)
{
double currentValue = mixedDistro[index];
std::string test = std::to_string(currentValue);
if(std::regex_search(test, dbl)) \\I also tried with match
{
detected++;
}
}
printf("Number of points detected: %d\n", detected);
}
更新:以下源代码现在可以按预期工作:
void detectFormatConsistency()
{
std::regex dbl("^[+-]?[0-9]+(\\.[0-9]{2,4})$");
std::smatch matches;
int detected = 0;
for(unsigned int index = 0; index < mixedDistro.size(); index++)
{
double currentValue = mixedDistro[index];
std::string test = tostring(currentValue);
if(std::regex_match(test, dbl))
{
detected++;
}
}
printf("Number of points detected: %d\n", detected);
}
//https://stackoverflow.com/questions/13686482/c11-stdto-stringdouble-no-trailing-zeros
//Thanks to: @Silencer
template<typename T>
std::string tostring(const T &n) {
std::ostringstream oss;
oss << n;
std::string s = oss.str();
unsigned int dotpos = s.find_first_of('.');
if(dotpos!=std::string::npos){
unsigned int ipos = s.size()-1;
while(s[ipos]=='0' && ipos>dotpos){
--ipos;
}
s.erase ( ipos + 1, std::string::npos );
}
return s;
}
感谢大家的帮助!
【问题讨论】:
-
正则表达式中的任何内容都不会阻止
0.0000匹配。它遵循这种模式,在.之前有一个0,后面有4 个。0.00不能在另一边匹配,因为后面只有 2 个0而您代码中的正则表达式要求至少 3 个。 -
我会检查
mixedDistro的值。此数组double vals[] = {0.00, 0.0000, 0.0, 0 };中的所有值都由std::to_string转换为0.000000。 -
您应该使用
std::regex_match,因为std::regex_search匹配任何子字符串。 -
此外,您问题中的正则表达式与代码中的正则表达式不同,并且 两者 都允许您说应该拒绝的模式...
-
“我已经尝试了许多正则表达式验证解决方案,它可以按预期工作。” - 你能提供一个以便我们比较吗?