使用正则表达式进行匹配。
[] : 字符集合
() : 分组
? : 重复 0 ~ 1 次
+ : 重复 1 ~ n 次
* : 重复 0 ~ n 次
. : 任意字符
\\. : 转义后的 .
\d : 数字
$ 匹配字符串的末尾。
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if not s:
return False
import re
return re.match("[+-]?\d*(\\.\d+)?([eE][+-]?\d+)?",s).group() == s
# return re.match("[+-]?[0-9]*([\\.][0-9]+)?([eE][+-]?[0-9]+)?", s).group() == s
# return re.match(r"^[\+\-]?[0-9]*(\.[0-9]*)?([eE][\+\-]?[0-9]+)?$", s)
# 加上$处理末尾 例如12e
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try :
p = float(s)
return True
except:
return False