【发布时间】:2016-10-09 05:49:36
【问题描述】:
我在 c++ 中有一个函数,它接受一个输入字符串,该字符串表示格式为 MM/DD/YYYY 的日期。由于我的环境的限制,该函数使用正则表达式的 C 实现。我正在尝试从字符串中提取年、月和日期。
#include <stdarg.h>
#include <string.h>
#include <iostream>
#include <regex.h>
#include <sys/types.h>
using namespace std;
void convertDate(string input)
{
char pattern[100];
regex_t preg[1];
regmatch_t match[100];
const char * reg_data = input.c_str();
string year;
string month;
string day;
strcpy(pattern, "^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$");
int rc = regcomp(preg, pattern, REG_EXTENDED);
rc=regexec(preg, reg_data, 100, match, 0);
if( rc != REG_NOMATCH )
{
year = input.substr(match[3].rm_so, match[3].rm_eo);
month = input.substr(match[1].rm_so, match[1].rm_eo);
day = input.substr(match[2].rm_so, match[2].rm_eo);
cout << year << endl;
cout << month << endl;
cout << day << endl;
}
}
以下是一些输入/输出示例:
1) string input2 = "8/11/2014";
convertDate(input2);
2014
8
11/2
2) string input2 = "11/8/2014";
convertDate(input2);
2014
11
8/20
3) string input2 = "1/1/2014";
convertDate(input2);
2014
1
1/2
我不确定这一天为什么要捕获长度为 4 的正则表达式组,当捕获组声明它应该只捕获 1 或 2 个数字字符时。另外,当月份正确时,为什么这一天会出现这个问题?他们使用相同的逻辑,看起来像。
我使用了文档here
【问题讨论】:
-
你使用的是什么编译器和版本?
-
我正在使用一个使用 c++11 的在线编译器。 See here@NathanOliver
-
好的。那是 gcc 5.3.1。我问是因为this
-
我明白了。所以这不是一个错误,因为它是比 4.8 更高的版本? @NathanOliver
-
@ThomasMatthews C 标准没有正则表达式。
<regex.h>is from POSIX。不过,对于 C++11,我们应该使用 C++'s standard<regex>library。