Context:
I am currently writing a date formatting library in C++. For example. the library takes in a formatting string such as: dddd, mmmm d, dddd yyyy
and produces a result Tuesday, December 26, Tuesday 2016
given year: 2016, month: 12, date: 26 (dddd
stands for weekday, d
stands for date in number, mmmm
stands for month, yyyy
stands for year).
I would like to achieve this by using boost::regex_replace
.
What I have tried:
Javascript
In javascript
I can easily achieve this by doing:
var pattern = 'dddd, mmmm d, yyyy';
pattern.replace(/(dddd)|(d)|(mmmm)|(yyyy)/gi, function (dddd, d, mmmm, yyyy){
if (dddd) {
return 'Tuesday';
}
if (d) {
return '26'
}
if (mmmm) {
return 'December';
}
if (yyyy) {
return '2016';
}
return '';
}
C++
boost::regex regex1("(dddd)");
boost::regex regex2("(d)");
boost::regex regex3("(mmmm)");
boost::regex regex4("(yyyy)");
boost::smatch match;
// dddd
if (boost::regex_search(pattern, match, regex1))
{
pattern = boost::regex_replace(pattern, regex1, "Tuesday");
}
// d
if (boost::regex_search(pattern, match, regex2))
{
pattern = boost::regex_replace(pattern, regex2, "26");
}
// mmmm
if (boost::regex_search(pattern, match, regex3))
{
pattern = boost::regex_replace(pattern, regex3, "December");
}
// yyyy
if (boost::regex_search(pattern, match, regex4))
{
pattern = boost::regex_replace(pattern, regex4, "2016");
}
However, that gives me a result of "Tues26ay, December 26, Tues26ay 2016"
. The reason is that: as soon as I replace pattern dddd
with Tuesday
, the d
inside Tuesday
becomes a target pattern for regex2
causing it to be replaced with 26
.
I am not sure how to fix this problem or I think my C++ way for solving this problem is not correct. Is it possible to have something similar as Javascript in C++ boost::regex?
Any help would be appreciated!