This is an example that might be more useful than creative.
It uses a variable length negative lookbehind starting from the last match (\G
)
checking forward to the current position.
In this case (?<!\Ga+)b
, the result is that it matches every other b
in a string where b's are separated by one or more a
's.
This can also be done in a fixed width lookbehind like (?<!\Ga)b
where the result is that it matches every other b
in a string where b's are separated by one a
.
This is kind of a template where a
and b
could be bigger expressions and have a little more
meaning.
(One thing to be aware of is that when using \G
in a negative lookbehind, it is fairly easy to
satisfy the negative assertion. So, these kind of things have gotcha
written all over it !!)
Don't have Python (latest, beta?) to test this with, so below is using C# console app.
string strSrc = "abaabaabaabaabaab";
Regex rxGtest = new Regex(@"(?<!\Ga+)b");
Match _m = rxGtest.Match(strSrc);
while (_m.Success)
{
Console.WriteLine("Found: {0} at position {1}", _m.Groups[0].Value, _m.Index);
_m = _m.NextMatch();
}
Output:
Found: b at position 4
Found: b at position 10
Found: b at position 16