Page 1 of 1

Is string a valid number check?

Posted: Mon Aug 06, 2012 10:11 pm
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

Re: Is string a valid number check?

Posted: Mon Aug 06, 2012 10:23 pm
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.