2017-01-23 122 views
2

我需要检查月份是否是01-12的形式。我做了一个正则表达式,并采取了输入来检查它是否匹配正则表达式。 代码 -Regexec()没有给出想要的结果

#include <iostream> 
#include<string> 
using namespace std; 
#include<regex.h> 
#include<stdio.h> 


int main() 
{ 
int a; 
cin>>a; 
cout << "Hello World" << endl; 
string mon; 
cin>>mon; 
string exp_month = mon; 
string monthRegex = "(0[1-9]|1[0-2])"; 
regex_t preg; 
int  rc; 

if (0 != (rc = regcomp(&preg, monthRegex.c_str(), REG_NOSUB))) { 
    cout<<("regcomp() failed, returning nonzero (%d)\n", rc); 
    exit(EXIT_FAILURE); 
    } 


if (regexec(&preg,exp_month.c_str(),0,NULL,0)==0) 
{ 
    cout<<"yess"; 
} 
else 
{ 
    cout<<"no"; 
} 
return 0; 
} 

输入 A = 09; mon = 09; 输出为“无”

但09匹配给定的正则表达式

+0

这是一个有趣的C和C++混合,为什么?另外,什么是“年”? –

+0

这不是[最小,完整和可验证的示例](https://stackoverflow.com/help/mcve) - 您可以删除与您的问题无关的大量代码。它也不能同时是C和C++,因为它们是不同的语言。同样你的缩进可能会更好。 – Useless

+0

对不起我还是新来的 我现在编辑了代码 –

回答

1

正则表达式似乎纠正。 尝试使用从C++ 11

cout << "Hello World" << endl; 
string mon; 
cin >> mon; 
string monthRegex = "(0[1-9]|1[0-2])"; 
std::regex rex (monthRegex); 

if (std::regex_match (mon, rex)) 
{ 
    std::cout << "Matched\n"; 
} 
else 
{ 
    std::cout << "Not matched\n"; 
} 
1

根据BRE POSIX标准的正则表达式(当你不所述REG_EXTENDED标志传递到regcomp),则|管交替操作,相同(/){n,m}字符只有当你逃脱时才会变得“特别”。当使用ERE POSIX正则表达式的味道(当你通过REG_EXTENDEDregcomp),它正好相反,转义()|{n,m}是特殊的。

所以,你的代码可以被固定为

string monthRegex = "0[1-9]\\|1[0-2]"; 

删除(和被视为BRE文字符号),管前添加转义符。

请参阅C++ demo

否则,使用REG_EXTENDED标志和使用自己的正则表达式:

rc = regcomp(&preg, monthRegex.c_str(), REG_NOSUB|REG_EXTENDED) 
                ^^^^^^^^^^^^ 

然而,最好是在C++代码中使用std::regex,看arturx64's answer

相关问题