SQL 正则表达式验证数据是否包含数字(或空也有效)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2551053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:50:45  来源:igfitidea点击:

Regular expression to validate whether the data contains numeric ( or empty is also valid)

sqlregexvalidation

提问by VInayK

i have to validate the data contains numeric or not and if it is not numeric return 0 and if it is numeric or empty return 1.

我必须验证数据是否包含数字,如果它不是数字返回 0,如果它是数字或空返回 1。

Below is my query i tried in SQL.

下面是我在 SQL 中尝试的查询。

SELECT dbo.Regex('^[0-9]','123')-- This is returning 1.

SELECT dbo.Regex('^[0-9]','123')-- 这是返回 1。

SELECT dbo.Regex('^[0-9]','')-- this is not returning 1 but i want to return as 1 and i try to put space in "pattern" also it is not working...

SELECT dbo.Regex('^[0-9]','')-- 这不是返回 1 但我想返回为 1 并且我尝试在“模式”中放置空间它也不起作用...

please can any one help....

请任何人可以帮助....

Thanks in advance

提前致谢

回答by cletus

Try:

尝试:

SELECT dbo.Regex('^[0-9]*$','123')

or better yet:

或者更好:

SELECT dbo.Regex('^\d*$','123')

\dis standard shorthand for [0-9]. Note that when you use [0-9]it means "match exactly one digit. The *wildcard means match zero or more so \d*means match zero or more digits, which includes an empty result.

\d是 的标准简写[0-9]。请注意,当您使用[0-9]它时,它表示“仅匹配一位数字。*通配符表示匹配零个或多个,因此\d*表示匹配零个或多个数字,其中包括空结果。

回答by Jens

Your Regex is not quite right: "^[0-9]"checks only, if the first character in the string is a number. Your regex would return 1on "3abcde".

您的正则表达式不太正确:"^[0-9]"仅检查字符串中的第一个字符是否为数字。您的正则表达式将返回1“3abcde”。

Use

"^\d*$"

to check if the field contains only numbers (or nothing). If you want to allow whitespace, use

检查该字段是否仅包含数字(或不包含任何内容)。如果要允许空格,请使用

"^\s*\d*\s*$"

If you want to allow signs and decimals, try

如果您想允许符号和小数,请尝试

"^\s*(+|-)?\d*\.?\d*\s*$"

回答by Amber

Try ^[0-9]*$, which will match 0 or more digits only:

Try ^[0-9]*$,它将仅匹配 0 个或多个数字:

SELECT dbo.Regex('^[0-9]*$','')

should return 1, as should...

应该返回 1,应该......

SELECT dbo.Regex('^[0-9]*$','123')