Use regular expressions to determine whether a string represents a numeric value

refers to a problem in offer, please implement a function to determine whether a string represents a numeric value (including integers and decimals). For example, the strings "+ 100"," 5e2 ","-123", "3.1416" and "- 1E-16" all represent numeric values. But "12e", "1a3.14", "1.2.3", "+-5" and "12e+4.3" are not.

import re
s = "12e"
pattern = "[\ + -]? [0-9] (\. [0-9] )? (eE? [0-9] +)?"
if re.match (pattern,s)! = None:
print (" legal")

I want to write with rules, but I"m not familiar with rules. I refer to an example on the Internet, but I didn"t pass all the test cases.
another, (eE? [0-9] +)? This expression means that eE? [0-9] + exists once or not, assuming it exists, e or E must be followed by a number to meet the expression, the expression seems to be correct, do not know where there is a problem, please point out, thank you.


I don't think this is the right way to write it. Just follow your rules when writing the rules (you didn't make your rules clear, so I followed my own rules):

  • an integer without an exponent must have an integer part. The positive sign can be omitted: [\ + -]?\ d + . This is why the plus sign is optional, the symbol cannot be omitted, and there can be several integers leading 0 . You might as well use the symbol Int to denote this regular expression;
  • A decimal without an index must not only have an integer part, but must also have a decimal part that begins with . : Int plus \.\ d + , that is, [\ + -]?\ d +\.\ d + . You might as well use the symbol Float to denote this regular expression;
  • A number without an index (integer or decimal) must have an integer part, and the decimal part that begins with . is optional: Int plus (\.\ d +)? , that is, [\ + -]?\ d + (\.\ d +)? . You might as well use the symbol Number to denote this regular expression;
  • A number with an index (integer or decimal) that begins with e or E . The index must be an integer: Number (base) plus [eE] plus Int , that is, [\ + -]?\ d + (\.\ d +)? [eE] [\ + -]?\ d + . You might as well use the symbol ENumber to denote this regular expression;

Summary : a legal number, the base part must contain an integer part, and its fractional part is optional; the index part is optional, and if there is, it must start with e or E , and the index is a previously defined integer.

result : [\ + -]?\ d + (\.\ d +)? ([eE] [\ + -]?\ d +)? . The outermost two (.)? denote "the fractional part of the base part is optional" and "the exponential part is dispensable", respectively.

if you want to judge rather than match, type trim and add ^ and $ before and after the original regular.


^[-+]?(?:[1-9]\d*|0)(?:\.\d+)?(?:[eE][-+]?\d+)?$
Menu