T-SQL 社会安全号码的正则表达式(SQL Server 2008 R2)

T-SQL Regex for social security number (SQL Server 2008 R2)

我需要在 SQL Server 2008 数据库 table 的 varchar 字段中查找无效的社会安全号码。 (有效 SSN 的定义格式为 ###-##-#### - 数字是什么并不重要,只要它们处于“3 位短划线 2 位短划线 4 位数字”模式中即可。

我有一个有效的正则表达式:

SELECT * 
FROM mytable
WHERE ssn NOT LIKE '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]'

这确实在列中找到了无效的 SSN,但我知道(好吧 - 我很确定)有一种方法可以缩短它以指示先前的模式可以有 x 次迭代。

我认为这行得通:

'[0-9]{3}-[0-9]{2}-[0-9]{4}'

但事实并非如此。

是否有比 select 中的上述正则表达式更短的正则表达式?或者可能有,但是 T-SQL/SQL Server 2008 不支持!?

如果您打算使用更短的 LIKE 表达式变体,那么答案是否定的。

T-SQL中,您只能在模式中使用以下通配符:

%
- Any string of zero or more characters. WHERE title LIKE '%computer%' finds all book titles with the word computer anywhere in the book title.

_ (underscore)
Any single character. WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ]
Any single character within the specified range ([a-f]) or set ([abcdef]). WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.
[^]
Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

所以,您的 LIKE 语句已经是最短的表达式了。不能使用限定量词(比如 {min,max}),不能使用 shorthand 类,比如 \d.

如果您使用的是 MySQL,则可以使用一组更丰富的正则表达式实用程序,但事实并非如此。

我建议你使用另一个这样的解决方案:

-- Use `REPLICATE` if you really want to use a number to repeat
Declare @rgx nvarchar(max) = REPLICATE('#', 3) + '-' +
                             REPLICATE('#', 2) + '-' +
                             REPLICATE('#', 4);

-- or use your simple format string
Declare @rgx nvarchar(max) = '###-##-####';

-- then use this to get your final `LIKE` string.
Set @rgx = REPLACE(@rgx, '#', '[0-9]');

你也可以使用类似 '_' 的字符,然后将其替换为 [A-Z] 等等。