如何在C++中使用每次匹配调用的函数来正则表达式替换字符串



我如何在现代C++中编写类似于以下Javascript代码的东西:

// Example Code From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^d]*)(d*)([^w]*)/, replacer);
console.log(newString);  // Prints 'abc - 12345 - #$*%'
#include<regex>
#include<string>
#include<iostream>
std::string foo(std::string s)
{
static const std::regex r {R"~~(^([^d]*)(d*)([^w]*)$)~~"};
return std::regex_replace(s, r, "$1 - $2 - $3");
}
int main()
{
std::string s = "abc12345#$*%";
std::cout << foo(s);
}

您可以使用以下regex将字符串拆分到所需的位置,在连续字符之间:

(?<=[a-z])(?=[0-9#$*%])|(?<=[0-9])(?=[a-z#$*%])|(?<=[#$*%])(?=[a-z0-9])

演示

正则表达式执行以下操作:

(?<=[a-z])      # match is preceded by a lc letter
(?=[0-9#$*%])   # match is followed by a digit or punctuation char
|               # or
(?<=[0-9])      # match is preceded by a lc letter
(?=[a-z#$*%])   # match is followed by a lc letter or punctuation char
|               # or
(?<=[#$*%])     # match is preceded by a lc letter
(?=[a-z0-9])    # match followed by a lc letter or digit

最新更新