首页 > 解决方案 > 正则表达式的最大长度是多少?

问题描述

desc在 PostgreSQL 中,如果字段包含任何禁止的单词,我想排除行。

items

| id | desc             |
|----|------------------|
| 1  | apple foo cat bar|
| 2  | foo bar          |
| 3  | foocatbar        |
| 4  | foo dog bar      |

禁用词列表存储在另一个表中,目前它有 400 个单词要检查。

forbidden_word_table

| word    |
|---------|
| apple   |
| boy     | 
| cat     | 
| dog     | 
| ....    | 

SQL查询:

select id, desc
from items
where
desc !~* (select '\y(' || string_agg(word, '|') || ')\y' from forbidden_word_table)

我正在检查是否desc与正则表达式不匹配:

desc !~* '\y(apple|boy|cat|dog|.............)\y'

结果:

| id | desc             |
|----|------------------|
| 2  | foo bar          |
| 3  | foocatbar        |

** 3rd 不被排除,因为cat它不是一个单词

forbidden_word_table的行数可能会增长,上面的正则表达式将成为一个非常冗长的表达式。

正则表达式是否有最大长度限制(以字节或字符为单位)?我担心如果forbidden_word_table不断增长,我的正则表达式匹配方法将不起作用。

标签: regexpostgresql

解决方案


看来,Wiktor Stribiżew关于“灾难性的回溯”是正确的。

我建议使用ILIKEANY

SELECT *
FROM items i
WHERE NOT i."desc" ILIKE ANY
(
  SELECT '%' || word || '%'
  FROM forbidden_word_table
);

db小提琴


推荐阅读