A regular expression question

Ben Finney ben+python at benfinney.id.au
Thu Sep 29 01:12:06 EDT 2016


Cpcp Cp <cpxuvs at gmail.com> writes:

> Look this
>
> >>> import re
> >>> text="asdfnbd]"
> >>> m=re.sub("n*?","?",text)
> >>> print m
> ?a?s?d?f?n?b?d?]?
>
> I don't understand the 'non-greedy' pattern.

Since ‘n*’ matches zero or more ‘n’s, it matches zero adjacent to every
actual character.

It's non-greedy because it matches as few characters as will allow the
match to succeed.

> I think the repl argument should replaces every char in text and
> outputs "????????".

I hope that helps you understand why that expectation is wrong :-)

Regular expression patterns are *not* an easy topic. Try experimenting
and learning with <URL:http://www.regexr.com/>.

-- 
 \      “If I haven't seen as far as others, it is because giants were |
  `\                           standing on my shoulders.” —Hal Abelson |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list