Reputation: 341
I have a string "minDate=2013-12-01T08:00:00Z&maxDate=2014-01-01T12:00:00Z" So i need the min and max date in output. The Regex which i use is "minDate=(.*?)(?:maxDate=)(.*)"
I get the correct output :
Full match `minDate=2013-12-01T08:00:00Z&maxDate=2014-01-01T12:00:00Z`
Group 1. `2013-12-01T08:00:00Z;`
Group 2. `2014-01-01T12:00:00Z`
Now the problem is "minDate" or "maxDate" can be optional. Means the input can be either:
minDate=2013-12-01T08:00:00Z&maxDate=2014-01-01T12:00:00Z
or
minDate=2013-12-01T08:00:00Z
or
maxDate=2014-01-01T12:00:00Z
What will be the Regex for this so that:
for first input i should get Group 1 '2013-12-01T08:00:00Z' and Group 2 as '2014-01-01T12:00:00Z'
and for second input i should get Group1 '2013-12-01T08:00:00Z'
and for third input i should get Group1 '2014-01-01T12:00:00Z'
Upvotes: 1
Views: 99
Reputation: 626893
You may match and capture minDate
or maxDate
into Group 1 and the datetime value into Group 2, and then you can assign the variables in your program as needed:
std::string maxDate = "";
std::string minDate = "";
std::regex r("(min|max)Date=([0-9-]+T[0-9A-Z:]+)");
std::string s = "minDate=2013-12-01T08:00:00Z&maxDate=2014-01-01T12:00:00Z";
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
i != std::sregex_iterator();
++i)
{
std::smatch m = *i;
if (m[1].str()=="min") {
minDate = m[2].str();
std::cout << "Min date: " << minDate << endl;
} else {
maxDate = m[2].str();
std::cout << "Max date: " << maxDate << endl;
}
}
See the C++ demo
Output:
Min date: 2013-12-01T08:00:00Z
Max date: 2014-01-01T12:00:00Z
Pattern details
(min|max)
- Capturing group 1 (this value is checked against): either min
or max
Date=
- a literal string Date=
([0-9-]+T[0-9A-Z:]+)
- Capturing group 2 (its value is the result): one or more digits or/and -
, then T
, then one or more uppercase ASCII letters, digits or/and :
.Upvotes: 1