sumeetmufc
sumeetmufc

Reputation: 11

Regular expressions in python. Incorrect output

I want to check if the string starts off with a number and then has 9 alpha-numeric characters. However, this returns yes instead of no. Why?

import re

if re.search(r'[0-9][0-9]{9}','92211sssff222'):
    print "yes"
else:
    print "no"

Upvotes: 1

Views: 64

Answers (2)

fferri
fferri

Reputation: 18950

The alphanumeric range should be something like [A-Za-z0-9]. Also, since you want the string to start with this format, put the ^ (beginning of string) symbol, to match it exactly, otherwise a string such as ' !!!92211sssff222' would match as well.

Fixed code:

import re

if re.search(r'^[0-9][A-Za-z0-9]{9}','92211sssff222'):
    print "yes"
else:
    print "no"

Upvotes: 1

The6thSense
The6thSense

Reputation: 8335

It should be like this .Since you said it should start you have to use the cap symbol ^ which specifies the start

As per your regex you are matching ten continues number which can happen anywhere in the string

import re

if re.search(r'^[0-9][a-zA-Z0-9]{9}','9sssssssff222'):
    print ("yes")
else:
    print ("no")

yes

Upvotes: 1

Related Questions