简体   繁体   English

SQL 服务器 - 正则表达式模式仅匹配字母数字字符

[英]SQL Server - Regex pattern match only alphanumeric characters

I have an nvarchar(50) column myCol with values like these 16-digit, alphanumeric values, starting with '0': 0b00d60b8d6cfb19, 0b00d60b8d6cfb05, 0b00d60b8d57a2b9我有一个 nvarchar(50) 列myCol ,其值类似于这些 16 位字母数字值,以“0”开头: 0b00d60b8d6cfb19, 0b00d60b8d6cfb05, 0b00d60b8d57a2b9

I am trying to delete rows with myCol values that don't match those 3 criteria.我正在尝试删除myCol值与这 3 个条件不匹配的行。

By following this article , I was able to select the records starting with '0'.通过关注这篇文章,我能够 select 以“0”开头的记录。 However, despite the [a-z0-9] part of the regex, it also keeps selecting myCol values containing special characters like 00-d@!b8-d6/f&#b .但是,尽管[a-z0-9]是正则表达式的一部分,它还会继续选择包含00-d@!b8-d6/f&#b等特殊字符的myCol值。 Below is my select query:下面是我的 select 查询:

SELECT * from Table
WHERE myCol LIKE '[0][a-z0-9]%' AND LEN(myCol) = 16

How should the expression be changed to select only rows with myCol values that don't contain special characters?应该如何将表达式更改为 select 只有myCol值不包含特殊字符的行?

If the value must only contain az and digits, and must start with a 0 you could use the following:如果该值必须只包含 az 和数字,并且必须以0开头,您可以使用以下内容:

SELECT *
FROM (VALUES(N'0b00d60b8d6cfb19'),
            (N'0b00d60b8d6cfb05'),
            (N'0b00d60b8d57a2b9'),
            (N'00-d@!b8-d6/f&#b'))V(myCol)
WHERE V.myCol LIKE '0%' --Checks starts with a 0
  AND V.myCol NOT LIKE '%[^0-9A-z]%' --Checks only contains alphanumerical characters
  AND LEN(V.myCol) = 16;

The second clause works as the LIKE will match any character that isn't an alphanumerical character.第二个子句起作用,因为LIKE将匹配任何字母数字字符的字符。 The NOT then (obviously) reverses that, meaning that the expression only resolves to TRUE when the value only contains alphanumerical characters. NOT然后(显然)反转了这一点,这意味着只有当值包含字母数字字符时,表达式才会解析为 TRUE。

Pattern matching in SQL Server is not awesome, and there is currently no real regex support. SQL 服务器中的模式匹配不是很好,目前没有真正的正则表达式支持。

The % in your pattern is what is including the special characters you show in your example.模式中的%包括您在示例中显示的特殊字符。 The [a-z0-9] is only matching a single character. [a-z0-9]仅匹配单个字符。 If your character lengths are 16 and you're only interested in letters and numbers then you can include a pattern for each one:如果你的字符长度是 16,而你只对字母和数字感兴趣,那么你可以为每个字符添加一个模式:

SELECT *
FROM Table
WHERE myCol LIKE '[0][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]';

Note: you don't need the AND LEN(myCol) = 16 with this.注意:你不需要AND LEN(myCol) = 16这个。

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

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