Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #197872
| From | Jon Ribbens <jon+usenet@unequivocal.eu> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work? |
| Date | 2026-08-09 01:26 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <slrn117flpd.2jr.jon+usenet@raven.unequivocal.eu> (permalink) |
| References | <1158h6s$1ts3e$1@dont-email.me> |
On 2026-08-09, Veek M <veekjunk@foobar.com> 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).
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work? Veek M <veekjunk@foobar.com> - 2026-08-09 00:21 +0000
Re: re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work? Jon Ribbens <jon+usenet@unequivocal.eu> - 2026-08-09 01:26 +0000
Re: re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work? ram@zedat.fu-berlin.de (Stefan Ram) - 2026-08-09 11:24 +0000
Re: re.sub(r'((?<=\A)|(?<=,))(?=,|\Z)', 'NA', ',1,,,two,3,,,') how does it work? Veek M <veekjunk@foobar.com> - 2026-08-11 09:21 +0000
csiph-web