How to determine the type of regexp?

# To the function is a string.
# It is not guaranteed that the string will be correct and 
#~ to contain a proper number.
import re
def foo(s):
 if some_regexp_int: #check for int
return(int(s))
 elif some_regexp_float: # check for float
return(float(s))
else:
 print('Uncorrect string!!')
# What you need to use the re
#~ to satisfy one of two conditions,
#~ with that, except the numbers in the line should not be anything
#~ (guaranteed: gaps will not be even in numbers)?
September 26th 19 at 05:59
3 answers
September 26th 19 at 06:01
Solution
re.match("[0-9]+", s)
re.match("[0-9]+.[0-9]+", s)

If possible a negative number, add an optional "-" in the beginning
September 26th 19 at 06:03
Solution
def convert(x):
 for func in (int, float, complex):
try:
 return func(x)
 except ValueError:
pass
 return float('NaN')
September 26th 19 at 06:05
Aside from regular expressions, it is possible to implement this (Python 2.7):
def foo(s):
try:
s_int=int(s)
 return s_int
 except ValueError:
try:
s_float=float(s)
 return s_float
 except ValueError:
 print "invalid string!"

print foo('123')
print foo('123.5')
print foo('1e-10')
print foo('toster')

Of the benefits of such an approach is supported by scientific notation (1e-10). But I'm not sure about the performance, and other nuances.

Find more questions by tags PythonRegular expressions