I’m trying to write a function in python, which will determine what type of value is in string; for example
if in string is 1 or 0 or True or False the value is BIT
if in string is 0-9*, the value is INT
if in string is 0-9+.0-9+ the value is float
if in string is stg more (text, etc) value is text
so far i have stg like
def dataType(string):
odp=''
patternBIT=re.compile('[01]')
patternINT=re.compile('[0-9]+')
patternFLOAT=re.compile('[0-9]+\.[0-9]+')
patternTEXT=re.compile('[a-zA-Z0-9]+')
if patternTEXT.match(string):
odp= "text"
if patternFLOAT.match(string):
odp= "FLOAT"
if patternINT.match(string):
odp= "INT"
if patternBIT.match(string):
odp= "BIT"
return odp
But i’m not very skilled in using regexes in python..could you please tell, what am i doing wrong? For example it doesn’t work for 2010-00-10 which should be Text, but is INT or 20.90, which should be float but is int
Before you go too far down the regex route, have you considered using ast.literal_eval
Examples:
May as well use Python to parse it for you!
OK, here is a bigger example:
Output:
And if you positively MUST have a regex solution, which produces the same results, here it is:
I cannot recommend the regex over the ast version however; just let Python do the interpretation of what it thinks these data types are rather than interpret them with a regex…