Regular Expression

How to match the string in the following format 12\15\13 using regular expression.
The format is not changing but data will change like 11\22\14.
Do not consider date format and consider only it is a string.
Sounds like homework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string> /* string operations */
#include <iostream> /* std::cout, std::endl */
char* as_date(int month, int day, int year)
{
    std::string return_value (std::to_string(month));
    return_value += "\\";
    return_value += std::to_string(day);
    return_value += "\\";
    return_value += std::to_string(year);
    return const_cast<char*>(return_value.c_str());
}

int main()
{
    char* date = as_date(12,15,13);
    std::cout<<date<<std::endl;


}


;)
Last edited on
this code is totaly new to me :P
will yo u explain it. Like you are the teacher .. and teaching your students....
because i am new in c++
Regular expressions are pattern matching, so for everything in your string, you want to write a pattern that will match it.

12\15\13

Looks like:

    2 digits, followed by
    a backslash, followed by
    2 digits, followed by
    a backslash, followed by
    2 digits.

So if the string looks like that, then it matches. That's what a regular expression does -- checks to see if a string matches its patterns.

Write your regular expression the same way. Hint: how do you match a digit in an re? How do you match a backslash?


I don't know why your professor wants you to use backslashes -- they are one of the more unusual separators for dates, and they are particularly obnoxious in an re. In an re, you must 'escape' them -- that is, double them. Then, in C++, you must 'escape' them again.

So for a single backslash in an re, you must write four in C++:

    "\\\\"    matches the string    \

Hope this helps.
Last edited on
Topic archived. No new replies allowed.