I am trying to check if a string
contains only valid number in the following format
123.456
123
.356
But it should reject anything that contains non-numbers including double dots. Here are some invalid formats
d123.456
123d
12d3
d.1256
12d.456
12.d12
12.d45d
12.45.56
I have done the following
SELECT CASE WHEN '123.00' NOT LIKE '%[^0-9.]%' THEN 'Valid' ELSE 'Invalid' END
When seems to work except for the case where there is more than one dot in the string.
How can I tweak the regular expression to only allow one dot otherwise return 'Invalid'?
Using Character. isDigit(char ch). If the character is a digit then return true, else return false.
Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.
Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
I would suggest try_convert()
:
select (case when try_convert(col, float) is not null then 'valid' else 'invalid' end)
The one possible downside is exponential format; 1e6
is a valid number for instance.
An alternative is the where
approach; you just need more complete logic:
select (case when col like '%[^0-9.]%' then 'invalid'
when col like '%.%.%' then 'invalid'
else 'valid'
end)
There's a sql server built in function:
Select CASE WHEN isnumeric([fieldname]) THEN 'Valid' ELSE 'Invalid" END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With