问题
你想要一个负无限宽度的正则表达式:
(?<=(^|[^%])(?:%%)*)\d+
这里是.NET regex demo
在 ES7 中,不支持它,您需要使用特定于语言的方法和简化的正则表达式来匹配数字序列之前的任意数量的 %:/(%*)(\d+)/g,然后在 replace 回调中检查是否百分号的数量是偶数还是非偶数,并相应地进行。
JavaScript
您可以只使用 JS 手段,而不是尝试模拟可变宽度的lookbehind:
var re = /(%*)(\d+)/g; // Capture into Group 1 zero or more percentage signs
var str = 'abcd %1 %%2 %%%3 %%%%4 efgh<br/><br/>abcd%12%%34%%%666%%%%11efgh';
var res = str.replace(re, function(m, g1, g2) { // Use a callback inside replace
return (g1.length % 2 === 0) ? g1 + '(.+)' : m; // If the length of the %s is even
}); // Return Group 1 + (.+), else return the whole match
document.body.innerHTML = res;
如果数字前必须至少有 2 个%,请使用/(%+)(\d+)/g 正则表达式模式,其中%+ 至少匹配1 个(或更多)百分号。
转换为 C++
在 C++ 中可以使用相同的算法。唯一的问题是std::regex_replace 中没有对回调方法的内置支持。可以手动添加,使用方式如下:
#include <iostream>
#include <cstdlib>
#include <string>
#include <regex>
using namespace std;
template<class BidirIt, class Traits, class CharT, class UnaryFunction>
std::basic_string<CharT> regex_replace(BidirIt first, BidirIt last,
const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
std::basic_string<CharT> s;
typename std::match_results<BidirIt>::difference_type
positionOfLastMatch = 0;
auto endOfLastMatch = first;
auto callback = [&](const std::match_results<BidirIt>& match)
{
auto positionOfThisMatch = match.position(0);
auto diff = positionOfThisMatch - positionOfLastMatch;
auto startOfThisMatch = endOfLastMatch;
std::advance(startOfThisMatch, diff);
s.append(endOfLastMatch, startOfThisMatch);
s.append(f(match));
auto lengthOfMatch = match.length(0);
positionOfLastMatch = positionOfThisMatch + lengthOfMatch;
endOfLastMatch = startOfThisMatch;
std::advance(endOfLastMatch, lengthOfMatch);
};
std::sregex_iterator begin(first, last, re), end;
std::for_each(begin, end, callback);
s.append(endOfLastMatch, last);
return s;
}
template<class Traits, class CharT, class UnaryFunction>
std::string regex_replace(const std::string& s,
const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
return regex_replace(s.cbegin(), s.cend(), re, f);
}
std::string my_callback(const std::smatch& m) {
if (m.str(1).length() % 2 == 0) {
return m.str(1) + "(.+)";
} else {
return m.str(0);
}
}
int main() {
std::string s = "abcd %1 %%2 %%%3 %%%%4 efgh\n\nabcd%12%%34%%%666%%%%11efgh";
cout << regex_replace(s, regex("(%*)(\\d+)"), my_callback) << endl;
return 0;
}
请参阅IDEONE demo。
特别感谢回调代码发到John Martin。