SQL - 在 LIKE 查询中包含空格以过滤包含脏话的内容

SQL - Including whitespace in LIKE query for filtering content include swear words

我在 SQL 服务器中有一个 table 的脏话,我使用 LIKE 查询在文本中搜索 table 中的单词。我需要一种方法在 LIKE 查询中的发誓词周围包含 whitespaces,如下所示:

... LIKE '%{whitespace}SWEAR-WORD{whitespace}%';

在脏话周围放置 space 是不够的,因为它可以是我语言中另一个正常单词的一部分(例如 'inter' 是 'international' 的一部分或 'pointer').

我尝试过的另一个解决方案是使用这个:

... LIKE '%[^a-zA-Z]SWEAR-WORD[^a-zA-Z]%';

但这对我不起作用。

有什么办法吗?或者除了 LIKE 查询之外还有其他解决方案吗?

编辑: 为了更好地理解,这是我们目前查找脏话的方式:

我们有一个名为 Reviles 的 table,它有 2 列(Id 和 Text)并且包含受限制的单词和短语。我们使用此查询来查明内容是否包含任何这些受限制的字词和短语:

IF EXISTS (SELECT * dbo.Reviles WHERE @Text LIKE '%' + dbo.Reviles.Text + '%')
  @IsHidden = 0

请注意,此检查是在将内容插入其 table 之前完成的。上面的代码是存储过程的一部分,它获取 post 的信息并在插入之前检查各种内容,包括脏话。

之前我们在 table 中存储了像 'swear-word' 这样的受限词,但是这样我们就无法找到并隐藏行首或行尾带有脏话的内容,或者仅包含一个脏话的内容。例如: This is my content with a swear-word 要么 Swear-word in my content 要么 Swear-word 所以我们决定删除那些 spaces 并存储像 'swear-word' 这样的限制词。但是这会导致一些正常的内容被隐藏,因为一些脏话可以是另一个正常词的一部分(如果我们假设 inter 是一个坏词,那么 pointer 和 international 等将被限制)。

抱歉我的英语不好,我希望通过这个描述,我已经说清楚了。

我有点搞不懂你想做什么,如果你想像'{whitespace}swearword{whitespace}'那样做,那么使用like '% inter %'已经可以了

但如果您确实对过滤器有特殊要求,另一种方法是启用 SQL CLR,然后从 visualStudio 创建 Sql 函数并部署到 SQL 服务器。在 SQL 函数中,您可以使用正则表达式来 return 匹配或不匹配。

  1. 创建SQL 数据库项目
  2. 添加 SQL CLR(我使用 C#)
  3. 添加代码

    public partial class UserDefinedFunctions
    {
      [Microsoft.SqlServer.Server.SqlFunction]
      public static SqlBoolean RegularMatch(string str, string pattern)
      {
        var regex = new Regex(pattern);
        return new SqlBoolean (regex.IsMatch(str));
      }
    }
    
  4. Public 到 SQL 服务器

抱歉,我不擅长格式化。

尝试在某些字符中关闭您的检查语句,然后进行比较:

一些数据:

declare @T table(stmt nvarchar(20))
insert into @T values ('inter'),('Inter.'),('My inter'),
('intermediate!'),('pointer '),('Good inter'),('inter inter inter')

试试这个:

select
    stmt as stmt,
    case
        when '.'+stmt+'.' like '%[^a-z]inter[^a-Z]%' then 1 else 0 end as [has inter]
from
    @T

结果:

stmt                 has inter
-------------------- -----------
inter                1
Inter.               1
My inter             1
intermediate!        0
pointer              0
Good inter           1
inter inter inter    1