跳转至

3465. 查找具有有效序列号的产品

题目描述

表:products

+--------------+------------+
| Column Name  | Type       |
+--------------+------------+
| product_id   | int        |
| product_name | varchar    |
| description  | varchar    |
+--------------+------------+
(product_id) 是这张表的唯一主键。
这张表的每一行表示一个产品的唯一 ID,名字和描述。

编写一个解决方案来找到所有描述中 包含一个有效序列号 模式的产品。一个有效序列号符合下述规则:

  • SN 字母开头(区分大小写)。
  • 后面有恰好 4 位数字。
  • 接着是一个短横(-), 短横后面还有另一组 4 位数字
  • 序列号必须在描述内(可能不在描述的开头)

返回结果表以 product_id 升序 排序。

结果格式如下所示。

 

示例:

输入:

products 表:

+------------+--------------+------------------------------------------------------+
| product_id | product_name | description                                          |
+------------+--------------+------------------------------------------------------+
| 1          | Widget A     | This is a sample product with SN1234-5678            |
| 2          | Widget B     | A product with serial SN9876-1234 in the description |
| 3          | Widget C     | Product SN1234-56789 is available now                |
| 4          | Widget D     | No serial number here                                |
| 5          | Widget E     | Check out SN4321-8765 in this description            |
+------------+--------------+------------------------------------------------------+
    

输出:

+------------+--------------+------------------------------------------------------+
| product_id | product_name | description                                          |
+------------+--------------+------------------------------------------------------+
| 1          | Widget A     | This is a sample product with SN1234-5678            |
| 2          | Widget B     | A product with serial SN9876-1234 in the description |
| 5          | Widget E     | Check out SN4321-8765 in this description            |
+------------+--------------+------------------------------------------------------+
    

解释:

  • 产品 1:有效的序列号 SN1234-5678
  • 产品 2:有效的序列号 SN9876-1234
  • 产品 3:无效的序列号 SN1234-56789(短横后包含 5 位数字)
  • 产品 4:描述中没有序列号
  • 产品 5:有效的序列号 SN4321-8765

结果表以 product_id 升序排序。

解法

方法一:正则匹配

根据题意,我们需要找到所有包含有效序列号的产品,而有效序列号的规则是:

  • SN 开头(区分大小写)。
  • 紧接着是 4 位数字。
  • 必须有一个连字符 -,后面紧接着 4 位数字。

根据上述规则,我们可以使用正则表达式来匹配有效序列号,然后筛选出包含有效序列号的产品,最后按照 product_id 升序排序。

1
2
3
4
5
# Write your MySQL query statement below
SELECT product_id, product_name, description
FROM products
WHERE description REGEXP '\\bSN[0-9]{4}-[0-9]{4}\\b'
ORDER BY 1;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import pandas as pd


def find_valid_serial_products(products: pd.DataFrame) -> pd.DataFrame:
    valid_pattern = r"\bSN[0-9]{4}-[0-9]{4}\b"
    valid_products = products[
        products["description"].str.contains(valid_pattern, regex=True)
    ]
    valid_products = valid_products.sort_values(by="product_id")
    return valid_products

评论