Reputation: 11187
I am trying to find a regular expression which could be used to scan if a string is a number.
There are some examples here:
>>> expressions = [
"3",
"13.",
".328",
"41.16",
"+45.80",
"+0",
"-01",
"-14.4",
"1e12",
"+1.4e6",
"-2.e+7",
"01E-06",
"0.2E-20"
]
How can one capture all of these examples in a regular expression?
Upvotes: 0
Views: 98
Reputation: 2889
You can use [-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?'
to match numbers, but the solution @Cyber proposed is much better.
def filterPick(lines, regex):
matches = map(re.compile(regex).match, lines)
return [m.group() for m in matches if m]
print filterPick(expressions, '[-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?')
>>>['3', '13', '.328', '41.16', '+45.80', '+0', '-01', '-14.4', '1e12', '+1.4e6', '-20', '01E-06', '0.2E-20', '3']
Upvotes: 1
Reputation: 117856
This seems like a try
/except
block might be better in this situation
expressions = [
"3",
"13.",
".328",
"41.16",
"+45.80",
"+0",
"-01",
"-14.4",
"1e12",
"+1.4e6",
"-2.e+7",
"01E-06",
"0.2E-20",
"word",
"3ad34db"
]
for value in expressions:
try:
num = float(value)
print('{} is a number'.format(num))
except ValueError:
print('{} is not a number'.format(value))
Output
3.0 is a number
13.0 is a number
0.328 is a number
41.16 is a number
45.8 is a number
0.0 is a number
-1.0 is a number
-14.4 is a number
1000000000000.0 is a number
1400000.0 is a number
-20000000.0 is a number
1e-06 is a number
2e-21 is a number
word is not a number
3ad34db is not a number
Upvotes: 2