简体   繁体   English

检查字符串是否仅包含数字

[英]Check if a string contains only number

I am trying to check if a string contains only valid number in the following format我正在尝试检查string是否仅包含以下格式的有效数字

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'?如何调整正则表达式以仅允许一个点,否则返回“无效”?

I would suggest try_convert() :我建议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. 1e6是一个有效数字。

An alternative is the where approach;另一种方法是where方法; you just need more complete logic:你只需要更完整的逻辑:

select (case when col like '%[^0-9.]%' then 'invalid'
             when col like '%.%.%' then 'invalid'
             else 'valid'
        end)

TRY_PARSE will let you compare the input value to any/all numeric datatypes you decide to allow -- for example: TRY_PARSE将让您将输入值与您决定允许的任何/所有数字数据类型进行比较——例如:

SELECT 
   TRY_PARSE('123.456' as int) as [int],
   TRY_PARSE('123.0' as float) as [float],
   TRY_PARSE('d123.456' as int) as [int],
   TRY_PARSE('d123.456' as float) as [float]

FWIW -- ISNUMERIC is often suggested, and is certainly the best- sounding function name :-) -- but doesn't work the way most folks seem to expect. FWIW - 通常建议使用ISNUMERIC ,并且肯定是最好听的函数名称 :-) - 但它不像大多数人所期望的那样工作。 (It allows math and currency symbols, etc.) (它允许数学和货币符号等)

有一个内置的 sql server 函数:

Select CASE WHEN isnumeric([fieldname]) THEN 'Valid' ELSE 'Invalid" END

If you're not tied to regular expressions, SQL Server has an ISNUMERIC function you can use for this.如果您不依赖于正则表达式,SQL Server 有一个ISNUMERIC函数,您可以使用它。

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type;当输入表达式计算为有效的数值数据类型时,ISNUMERIC 返回 1; otherwise it returns 0.否则返回 0。

Alternative solution for NOT LIKE clause is: NOT LIKE子句的替代解决方案是:

where REGEXP_LIKE(column, '^[[:digit:]]+$')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM