[Tutor] Matching with beginning of the line in the character set

Kent Johnson kent37 at tds.net
Tue Feb 1 19:15:18 CET 2005

Smith, Jeff wrote:
> I want to match a string which is preceeded by a space or occurs at the
> beginning of the line.  I also don't want to catch the preceeding
> character as a group.
> I have found both of the following to work
> 	re.compile('(?:^|\s)string')
> 	re.compile('(?:\A|\s)string')

How about r'\bstring' ? It doesn't mean quite the same as \sstring but it might work for you.

> But would prefer to use the more concise [] notation.  However
> 	re.compile('[^\s]string')

As the first character in [], ^ means 'not'.

> Does not work and
> 	re.compile('[\A\s]string')

I guess \A doesn't count as a 'character class'? Or do you need to be using raw strings?


More information about the Tutor mailing list