Is string a valid number check?

Started by HPW, August 06, 2012, 03:11:10 PM

Previous topic - Next topic

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

#1
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:


<-- lead --><---- hex ---->|<- oct ->|<------- decimal ----- and ----- scientific ---->
{(s+|(|))(0x[0-9a-fA-F]+|[+-]?0d+|([+-]?(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.