What is an alternative for lookbehind with C++ RegEx?

ぐ巨炮叔叔 提交于 2019-12-06 06:06:01

问题


I am using the following pattern (?<=<)(?<!>).*?q.*?(?!<)(?=>) which uses positive and negative lookahead and lookbehind to match the literal q that is enclosed in matching brackets. C++ RegEx does not support lookbehind what would be a good alternative? Thanks!


回答1:


Note that (?<=<)(?<!>) is equal to (?<=<) (since a < is required immediately to the left of the current location, there cannot be any >) and (?!<)(?=>) is equal to (?=>) (same logic applies here, as > must be immediately to the right, there won't be any <). The first .*? will not match the shortest substring possible, it will literally find its way to the first q that is followed with any 0+ chars up to the first >. So, the pattern is hardly working for you even in the lookbehind-supporting engine.

I'd rather use <([^<>q]*q[^<>]*)> regex with a capturing group and literal consuming < and > symbols at the start/end of the expression:

std::regex r("<([^<>q]*q[^<>]*)>");
std::string s = "<adqsdq<><abc>5<abq>6<qaz> <hjfffffffk>";
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
                         i != std::sregex_iterator();
                         ++i)
{
    std::cout << (*i).str(1)  << srd::endl;
}

See the C++ demo

Output: abq and qaz



来源:https://stackoverflow.com/questions/43503110/what-is-an-alternative-for-lookbehind-with-c-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!