Take the 2-minute tour ×

I want to use regular expressions to find the word AT in a string, followed by at least one white space-character. I define the regex as follows:

p = re.compile('\s*AT\s')

to allow additional white space-characters just before the word searched. With that I want to match e.g.


but not cases with normal characters attached to the word, like


However, the following expression


does not return a match. Also regex like \bAT\b with or without the * do not work. I was following the example looking for the word class here, so I cannot understand where the problem is. Maybe because I have non-printable characters in my text?

share|improve this question
please post the full program including a the test scenario. –  Woot4Moo Oct 5 '12 at 14:42
add comment

2 Answers

up vote 1 down vote accepted

.match() checks if the regular expression matches at the start of the string; you want .search()

share|improve this answer
Thats it! I knew I got a correct answer within 2 minutes. You will get the hock in 10 minutes. –  Alex Oct 5 '12 at 14:45
add comment

Use the \b word boundary anchor instead of looking for whitespace to select words:

p = re.compile(r'\bAT\b')

The \b anchor will also match if AT is the first word in the string, or next to punctuation and not just whitespace (e.g. What about AT?).

You also want to use .search() instead of .match(); the latter automatically anchors to the start of the searched string:



>>> import re
>>> p = re.compile(r'\bAT\b')
>>> p.search('blah\rAT\r\n').group()
share|improve this answer
In [65]: pattern = re.compile(r'\bAT\b') In [66]: print pattern.match('a\rAT\r\n') None –  Alex Oct 5 '12 at 14:43
@Alex: That's why you want to use .search(), not .match(). –  Martijn Pieters Oct 5 '12 at 14:46
@Alex.. match() only matches at the beginning of the string.. if not found returns None.. –  Rohit Jain Oct 5 '12 at 14:49
add comment

Your Answer


