How do I validate a number decimal string?

I need help with string matching.

Been trying to use :match('%d*[%.%d]%d*') but it matches extra "."s.
I try not to use loops, just string.match. I don’t want to use tonumber either because that is hacky.

Examples;
15.42 works.
.42 works.
512 works.

.123. doesn’t work.
abc doesn’t work.
1 2 doesn’t work.
etc.

Those are not valid representations of decimals anyways. Just use tonumber. There is nothing “hacky” about it.

3 Likes

It seems to me you are trying to do like a match for any number.

So you would have to set it up to match any of those as well.

Really, just do tests in the input output views. So:

print( string.match(“Hello!!! I am another .123456.1243. string.”, “%d*[%.%d]%d*”) )

Then you can speed test them.

It seems to me that your code isn’t right.
%d*[%.%d]%d*

You want Magic Number All proceeding numbers, then Magic . then Magic numbers proceeding.

So “%d*%.%d*” So all numbers in a sequence, full stop, all numbers in a sequence. 1234.2345

But that will only match decimals with a number before the decimal.

For say “.54” where the 0 isn’t included, you would have to match “%.%d*”

For a whole number, you would have to match “%d*”

But you would look for full decimals first, if it doesn’t find any, then search for decimals without the 0. If it doesn’t find any, search for the whole number. If it doesn’t find any, return “There are no numbers in this string.”

That’s what I would do.

Just tested this
print( string.match(“Hello!!! I am .321.121 another string.”, “%.%d*%.%d*”) ) – Set
Got .321.121

But you will have to search for more than one and compare them. You can always store the result and remove check if there are more than 1 point then and if the first character is a point, then remove it.

You can also clean the string up first by removing any matches from the string if it’s not a number. So for instance a sentence. If it is a . without a number after it, then remove it.

It’s a lot of work but you can get it done in about 20-50 lines of code I believe.

Hi! I’m not sure what you are trying to do, as mentioned tonumber is often useful.

But it looks like your pattern is close to matching number decimal strings. It seems you forgot to specify that the string must start and end with your pattern:
‘^%d*[%.%d]%d*$’

Good luck!
Nonaz_jr

1 Like