mardi 4 août 2015

HTML ID value validation by RE

Problem Statement:

ID value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

I done by regular expression.

Code:

>>> import re
>>> id_value1 =  "custom-title1"
>>> id_value2 =  "1-custom-title"
>>> pattern = "[A-Za-z][\-A-Za-z0-9_:\.]*"

Code for valid ID value

>>> flag= False
>>> try:
...     if re.finadll(pattern, id_value1)[0]==id_value1:
...         flag=True
... except:
...     pass
... 
>>> print flag
False

Code for invalid ID value:

>>> flag = False
>>> try:
...     if re.findall(pattern, id_value2)[0]==id_value2:
...         flag=True
... except IndexError:
...     pass
... 
>>> print flag
False

Code for IndexError

>>> try:
...     if re.findall(pattern, "")[0]=="":
...         print "In "
... except IndexError:
...    print "Exception Index Error"
... 
Exception Index Error
>>> 

I will move above code in one function. This function will call more then 1000 times. So can anyone optimize above code?

Aucun commentaire:

Enregistrer un commentaire