Re: re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work?

Jon Ribbens via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Organization A noiseless patient Spider
Message-ID <[email protected]>
On 2026-08-09, Veek M <[email protected]> wrote:
> look-ahead look-behind don't consume string so how does it advance through 
> the string - could someone clearly explain how it works.
>
> re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') 
> 'NA,1,NA,NA,two,3,NA,NA,NA'

It's matching the empty string. It'll advance because once it's matched
at a certain position, the regular expression matcher will advance the
start position to the end of that match before checking for another
match.

> re.sub(r'(?<![^,])(?![^,])', 'NA', ',1,,,two,3,,,')
> 'NA,1,NA,NA,two,3,NA,NA,NA'

That's not doing differently to what the above expression doesn't
not do. It's trying to get around the limitation of lookbehind
assertions that every pattern they could match must be of the
same fixed length, by replacing "prior to the match must be the
start of the string, or prior to the match must be a comma" with
"prior to the match must not be a character that is not a comma".

> My understanding is that there has to be a pattern that consumes the 
> string eg: here [^,] consumes two 3 four and 5 but the look-ahead look-
> behind eliminate 5
>
> re.findall(r'(?<=,)[^,]+(?=,)', '1,two,3,four,5')
> ['two', '3', 'four']
>
> If it's matching the empty string '' then why don't we get NA,NA1 etc 
> for ,1

Because the empty string in-between the "," and the "1" fails the
lookahead assertion that after the match must be a comma or the
end of the string (or must not be a character that is not a comma,
in the second version).
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.