C ++ Boost正则表达式替换为条件 [英] C++ boost regex replace with conditions
问题描述
我目前正在用C ++写一个日期格式库.例如.该库采用格式字符串,例如: dddd,mmmm d,dddd yyyy
,并产生结果 2016年12月26日星期二,星期二
给定年份:2016,月份:12,日期:26( dddd
代表工作日, d
代表数字中的日期, mmmm
代表月份, yyyy
代表年份.
我想通过使用 boost :: regex_replace
来实现这一点.
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
.
在 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");
}
但是,这给了我"Tues26ay,December 26,Tues26ay 2016"
的结果.原因是:只要我将模式 dddd
替换为 Tuesday
, Tuesday
内的 d
就会成为目标regex2 的模式,导致将其替换为 26
.
我不确定如何解决此问题,或者我认为解决该问题的C ++方法不正确.是否有可能在C ++ boost :: regex中提供类似于Javascript的东西?
任何帮助将不胜感激!
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!
推荐答案
我不知道您为什么不按字面意义进行一对一翻译:
I don't know why you didn't literally 1-on-1 translate:
#include <boost/regex.hpp>
#include <iostream>
int main() {
std::string pattern = "dddd, mmmm d, yyyy";
pattern = boost::regex_replace(pattern, boost::regex("(dddd)|(d)|(mmmm)|(yyyy)"), [](auto& match)->std::string{
if (match.str() == "dddd")
return "Tuesday";
if (match.str() == "d")
return "26";
if (match.str() == "mmmm")
return "December";
if (match.str() == "yyyy")
return "2016";
return "";
});
std::cout << "Result: " << pattern << "\n";
}
打印
Result: Tuesday, December 26, 2016
奖金:
- c ++ 03版本在Coliru上直播
- 替代匹配选择子匹配索引上的C ++ 11 , 查看全文