在C++的正则表达式中捕获组
Capturing groups in regex in C++
我在 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 个数字字符。另外,当月份正确时,为什么这一天会有这个问题?他们使用相同的逻辑,看起来像。
我在这里使用了文档
您错误地使用了 .substr
方法。substr
的第二个参数应该是子字符串的长度,但你给它提供了结束索引。试试这个:
day = input.substr(match[2].rm_so, match[2].rm_eo - match[2].rm_so);
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- C++:正则表达式匹配代码,打印多个匹配项?