问题
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