Problem Statement :
The value of the identifier must begin with a letter ([A-Za-z]) and can be accompanied by any number of letters, numbers ([0-9]), hyphens ("-"), underscore ("_")), colons (": ") and periods (". ").
I made a regular expression.
The code:
>>> import re >>> id_value1 = "custom-title1" >>> id_value2 = "1-custom-title" >>> pattern = "[A-Za-z][\-A-Za-z0-9_:\.]*"
Code for a valid identifier 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 go above the code into one function. This function will call more than 1000 times. So can anyone optimize the code above?
source share