Is string a valid number check?

Q&A's, tips, howto's
Locked
HPW
Posts: 1390
Joined: Thu Sep 26, 2002 9:15 am
Location: Germany
Contact:

Is string a valid number check?

Post by HPW »

Hello,

What is the fastest way to check if a string is a valid number or not?
Or other way round to check it is a valid string only starting with a num char?
I have for example a string "1KR60". (float ) and (int ) makes a numer from it.
Would it be to check the string contain any ALPHA-chars?
A regex?

Regards

Hans-Peter
Hans-Peter

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Re: Is string a valid number check?

Post by Lutz »

Checking for alpha characters would not work, because you could have scientific notation, e.g. 1e123 or hex notation 0xabcdef and also octal.

In newlisp-x.x.x/util/syntax.cgi, I use the following regular expression pattern to identify legal numbers in newLISP:

Code: Select all

<-- lead --><---- hex ---->|<- oct ->|<------- decimal ----- and ----- scientific ---->
{(\s+|\(|\))(0x[0-9a-fA-F]+|[+-]?0\d+|([+-]?(0|[1-9]\d*)(\.\d*)?|\.\d+)([eE][+-]?\d+)?)}
It checks for decimals, hex, octals and floats in decimal point or scientific notation. For comma-separated decimals you would have to replace the \. with the \, in the decimal pattern part. Above patterns also allows for leading spaces.

Locked