tags:

views:

46

answers:

4

I'm trying to check if a string is a number, so the regex "\d+" seemed good. However that regex also fits "78.46.92.168:8000" for some reason, which I do not want, a little bit of code:

class Foo():
    _rex = re.compile("\d+")
    def bar(self, string):
         m = _rex.match(string)
         if m != None:
             doStuff()

And doStuff() is called when the ip adress is entered. I'm kind of confused, how does "." or ":" match "\d"?

+2  A: 

Change it from \d+ to ^\d+$

prostynick
+6  A: 

\d+ matches any positive number of digits within your string, so it matches the first 78 and succeeds.

Use ^\d+$.

Or, even better: "78.46.92.168:8000".isdigit()

eumiro
+1. Avoid regexps if you can.
Noufal Ibrahim
A: 

re.match() always matches from the start of the string (unlike re.search()) but allows the match to end before the end of the string.

Therefore, you need an anchor: _rex.match(r"\d+$") would work.

To be more explicit, you could also use _rex.match(r"^\d+$") (which is redundant) or just drop re.match() altogether and just use _rex.search(r"^\d+$").

Tim Pietzcker
A: 
>>> s="1234\n"
>>> re.search("^\d+\Z",s)
>>> s="1234"
>>> re.search("^\d+\Z",s)
<_sre.SRE_Match object at 0xb762ed40>
ghostdog74