模式匹配

在 SQL Server 数据库中清洗数据

Miriam Antona

Software Engineer

模式匹配 - 介绍

SELECT * FROM series
| id  | name            | contact_number | ... |
|-----|-----------------|----------------|-----|
| 1   | Adventure Time  | 555-906-8845   | ... |
| 2   | Dexter          | 555-156-8845   | ... |
| 3   | Futurama        | 555-210-9951   | ... |
| 4   | Game of Thrones | 555-543-6641   | ... |
| ... | ...             | ...            | ... |
  • 有效号码:###-###-####
    • 第 1 和第 4 个数字在 2 到 9 之间
    • 其余在 0 到 9 之间
  • 无效号码:555-156-8845
在 SQL Server 数据库中清洗数据

模式匹配 - 介绍

  • SQL Server 不提供完整的正则表达式集。
  • SQL Server 可用 LIKE 进行模式匹配。
  • 需完整正则功能 -> 创建并安装扩展。
在 SQL Server 数据库中清洗数据

模式匹配 - LIKE

  • 判断字符串是否匹配指定模式
在 SQL Server 数据库中清洗数据

模式匹配 - LIKE

  • 判断字符串是否匹配指定模式
通配符 说明 示例
% 任意长度(含零)字符串 WHERE contact_number LIKE '555-%'
_(下划线) 任意单个字符 WHERE contact_number LIKE '___-___-____'
[] 指定范围/集合内的任意单个字符 WHERE contact_number LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]
[^] 不在指定范围/集合内的任意单个字符 WHERE contact_number LIKE '[^2-9]'
在 SQL Server 数据库中清洗数据

模式匹配 - % 示例

SELECT name, contact_number
FROM series
WHERE contact_number LIKE '555%'
| name            | contact_number |
|-----------------|----------------|
| Adventure Time  | 555-906-8845   |
| Dexter          | 555-156-8845   |
| Futurama        | 555-210-9951   |
| Game of Thrones | 555-abc-6641   |
| ...             | ...            |
在 SQL Server 数据库中清洗数据

模式匹配 - % 示例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number NOT LIKE '555%'
| name            | contact_number |
|-----------------|----------------|
| The Good Doctor | 000-930-1274   |
在 SQL Server 数据库中清洗数据

模式匹配 - [](方括号)示例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'
| name           | contact_number |
|----------------|----------------|
| Adventure Time | 555-906-8845   |
| Futurama       | 555-210-9951   |
| Homeland       | 555-985-6314   |
| Westworld      | 555-456-1234   |
| ...            | ...            |
在 SQL Server 数据库中清洗数据

模式匹配 - [](方括号)示例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number NOT LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'
| name            | contact_number |
|-----------------|----------------|
| Dexter          | 555-156-8845   |
| Game of Thrones | 555-abc-6641   |
| The Good Doctor | 000-930-1274   |
在 SQL Server 数据库中清洗数据

Vamos praticar!

在 SQL Server 数据库中清洗数据

Preparing Video For Download...