regex puzzle

Alex Martelli aleax at aleax.it
Wed Nov 6 09:42:44 EST 2002


Mike Brown wrote:

> I need an example of a regular expression that:
> 
> - matches an empty string
> - matches a non-empty string
> - does NOT match a string consisting of only a linefeed
> 
> So, this test should produce [1, 1, 0]...
> 
> import re
> pat = '^(.+)?$' # FIXME
> [(re.search(pat, s) is not None) for s in ['', 'foo', '\n']]

import re
pat = r'\A(?!\n\Z)'
print [(re.search(pat, s) is not None) for s in 
       ['', 'foo', '\n', '\n\n' ]]

The "this test should produce" request can be satisfied without
the \Z, but I think you mean that '\n\n' should match (as it
doesn't consist of only a linefeed, but of two of them), and
for that you do need the \Z in the negative-lookahead assertion.


Alex




More information about the Python-list mailing list