Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

I am using the following pattern:

(?<=<)(?<!>).*?q.*?(?!<)(?=>)

It uses positive and negative lookahead and lookbehind to match the literal q that is enclosed in matching brackets.

std::regex does not support lookbehind. So what would be a good alternative?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...