Simple (?) Regular Expression Question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Steve Zatz

    Simple (?) Regular Expression Question

    Is '@' a special character in regular expressions? I am asking
    because I don't understand the following:
    [color=blue][color=green][color=darkred]
    >>> import re
    >>> s = ' @'
    >>> re.sub(r'\b@',' *',s)[/color][/color][/color]
    ' @'[color=blue][color=green][color=darkred]
    >>> s = ' a'
    >>> re.sub(r'\ba',' *',s)[/color][/color][/color]
    ' *'

    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.
  • Terry Carroll

    #2
    Re: Simple (?) Regular Expression Question

    On 18 Jan 2004 15:45:31 -0800, slzatz@hotmail. com (Steve Zatz) wrote:
    [color=blue]
    >Is '@' a special character in regular expressions? I am asking
    >because I don't understand the following:
    >[color=green][color=darkred]
    >>>> import re
    >>>> s = ' @'
    >>>> re.sub(r'\b@',' *',s)[/color][/color]
    >' @'[color=green][color=darkred]
    >>>> s = ' a'
    >>>> re.sub(r'\ba',' *',s)[/color][/color]
    >' *'
    >
    >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.[/color]

    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.


    Comment

    Working...