正则表达式匹配字符串中的日期包含:特殊字符,数字,字母

时间:2014-05-06 08:08:43

标签: c++ regex

我有以下正则表达式来提取日期模式:

  • ^\d{1,2}[-/. ]\d{1,2}[-/. ]\d{1,4}$

此正则表达式符合以下日期: 11/10 / 2004,19 / 20/1999 等。 但它与我有特殊字符的模式不匹配: aa(11/10/2004);,

即使它包含其他“字母,字符数字”

,我如何修改它以匹配日期

我删除了锚点部分但仍无法与日期匹配。 不匹配:26/11/2004),25/10/2003),


C ++:

#include <boost/regex.hpp>
#include <iostream>

using namespace std;

int main()
{
    string d = "25/10/2003),";
    const boost::regex e("\\d{1,2}[-/. ]\d{1,2}[-/. ]\\d{1,4}");
    bool x = boost::regex_match(d,e);
    if(x)
    {
        cout <<"found date" << endl;
    }

    return 0;

}

3 个答案:

答案 0 :(得分:3)

您只需删除将匹配锚定到字符串^$的开头和结尾的字符:

^.*\d{1,2}[-/. ]\d{1,2}[-/. ]\d{1,4}.*$

DEMO

答案 1 :(得分:1)

您使用了错误的功能。 regex_match是要确定的 给定的正则表达式是否与字符串完全匹配。 你想要的是regex_search,它搜索匹配 序列中的任何位置。

答案 2 :(得分:1)

以下代码适用于我。

regex regExDate("\\d{4}-\\d{2}-\\d{2}");
string date = "abc:\\2016-09-12";
smatch match;

if (regex_search(date, match, regExDate))
{
 string strDate = match.str();
}
相关问题