\s doesn't match
Lloyd Zusman
ljz at asfast.com
Fri Dec 24 14:09:12 EST 1999
<r at dslsubc13.ultracom.net> writes:
> I did this:
>
> a = 'a b'
> if match(r'\s',a): print 'error'
>
> and it didn't match.
>
> a = ' b'
>
> and it did match. Documentation seems to imply that \s matches
> whitespace anywhere in the string, what gives?
The `match' method matches characters anchored at the *beginning* of
the string. What follows is the first part of the documentation for
`match' ..
match (pattern, string)
Return how many characters at the beginning of string match the
regular expression pattern. [ ... ]
If you want to match for a pattern anywhere in the string, you should
use `search' and not `match', as follows ...
a = 'a b'
if search(r'\s',a): print 'error'
In other words, the `match' method works as if a `search' is being
done with an implied `^' character as the leftmost character of the
pattern ...
match(r'\s',a) is equivalent to search(r'^\s',a)
I hope this helps.
--
Lloyd Zusman
ljz at asfast.com
More information about the Python-list
mailing list