[Tutor] Symbol re question
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 18 Sep 2001 11:40:45 -0700 (PDT)
On Tue, 18 Sep 2001, Sean 'Shaleh' Perry wrote:
>
> On 18-Sep-2001 robert frank brenart wrote:
> >
> > Alright, this should be easy and it's being a pain... I just want to find
> > out if my string is all numbers.
> >
> > So I run...
> > if ((re.match("[0-9]+", mystring)) != None):
> > print "Pass"
> > else:
> > print "Fail"
> >
> > But that matches things like 10:45 and 3f, which I don't want it
> > to. What'm I overlooking?
> >
>
> A regex matches any part of a string. if you want the string to ONLY be
> numbers you need to say so in the regex. Try this:
>
> r"^[0-9]+$"
>
> that says "from the start of my string '^', match a string of numbers
> '[0-9]+' then the end of string '$'". The 'r' before the string tells
> python to read this as a raw string and should be used before any
> regex string.
Somewhat related: be aware that "match" is somewhat different from
"search" in Python's regular expressions:
http://www.python.org/doc/lib/matching-searching.html
If we're using the anchors '^' and '$', it might be good to use
re.search().