Simple (?) Regular Expression Question

Terry Carroll carroll at tjc.com
Sun Jan 18 20:29:55 EST 2004


On 18 Jan 2004 15:45:31 -0800, slzatz at hotmail.com (Steve Zatz) wrote:

>Is '@' a special character in regular expressions?  I am asking
>because I don't understand the following:
>
>>>> import re
>>>> s = ' @'
>>>> re.sub(r'\b@','*',s)
>' @'
>>>> s = ' a'
>>>> re.sub(r'\ba','*',s)
>' *'
>
>Have googled atsign and regular expressions but have not found
>anything useful.  System is Win XP, Python 2.3.3. Any help would be
>appreciated.

I suck at regular expressions, but I think that what's going on here is
that \b matches an empty string, but only at the start or end of a word.
In the first case ("\b@" and " @"), there is no start-of-word, so no
match, no substitution.

In the second case ("\ba" and " a", you have \b matching the empty string
between the blank and the "a", because the "a" is considered a word.

"a" is going to be considered a word, because it's entirely composed of
letters and numbers (a single letter), while "@" is not.





More information about the Python-list mailing list