Exact match with regular expression

Lie Ryan lie.1296 at gmail.com
Sun Oct 26 13:35:31 EDT 2008


On Sun, 26 Oct 2008 17:51:29 +0100, Mr.SpOOn wrote:

> Hi,
> I'd like to use regular expressions to parse a string and accept only
> valid strings. What I mean is the possibility to check if the whole
> string matches the regex.
> 
> So if I have:
> 
>>>> p = re.compile('a*b*')
> 
> I can match this: 'aaaaaabbb'
> 
>>>> m = p.match('aaaaaabbb')
>>>> m.group()
> 'aaaaaabbb'
> 
> But I'd like to get None with this: 'aabDDDDb' Instead it matches the
> first part:
> 
>>>> m = p.match('aabDDDDb')
>>>> m.group()
> 'aab'
> 
> I know this is the expected behaviour, but I'm sure it should be
> possible doing what I said.
> Are there other methods I don't know about in the re module?
> 
> Thanks.

re.compile('a*b*$')

$ matches the end of a string, or in MULTILINE mode, the end of a line 
(right before newline)

Symmetrically, ^ matches the start of a string, or in MULTILINE mode, the 
start of a line (including the start of the string)





More information about the Python-list mailing list