如何在MySQL /正则表达式替换器中计算单词数?

16

如何在MySQL查询中实现与Regex.Replace函数相同的行为(例如在.NET / C#中)?

我之所以需要这样做,是因为像许多人一样,我想计算字段中单词的数量。但是,我对以下答案不满意(在该网站上多次给出):

SELECT LENGTH(name) - LENGTH(REPLACE(name, ' ', '') +1 FROM table

因为在两个单词之间有超过一个空格时,它不能给出良好的结果。

顺便说一下,我认为Regex.Replace函数可能很有趣,所以欢迎所有好的想法!


出于好奇,为什么要计算字段中的单词数量? - Peter
4个回答

17

有一个REGEXP_REPLACE函数可以作为MySQL用户定义函数使用。

单词计数:如果您能够控制进入数据库的数据,您可以在插入之前删除双重空格。此外,如果您经常需要访问单词计数,您可以在代码中计算一次并将计数存储在数据库中。


1
更新:现在已经添加了一个适用于MySQL 8.0+的单独答案,应该优先使用。(保留此答案以防需要使用早期版本。) 几乎是这个问题的副本,但是这个答案将解决基于这篇博客文章中自定义正则表达式替换器的高级版本计算单词的用例。 演示 Rextester在线演示 对于样本文本,这给出了61个计数-与我尝试过的所有在线字数统计器相同(例如https://wordcounter.net/)。

SQL(为简洁起见,不包括函数代码):

SELECT txt,
       -- Count the number of gaps between words
       CHAR_LENGTH(txt) -
       CHAR_LENGTH(reg_replace(txt,
                               '[[:space:]]+', -- Look for a chunk of whitespace
                               '^.', -- Replace the first character from the chunk
                               '',   -- Replace with nothing (i.e. remove the character)
                               TRUE, -- Greedy matching
                               1,  -- Minimum match length
                               0,  -- No maximum match length
                               1,  -- Minimum sub-match length
                               0   -- No maximum sub-match length
                               ))
       + 1 -- The word count is 1 more than the number of gaps between words
       - IF (txt REGEXP '^[[:space:]]', 1, 0) -- Exclude whitespace at the start from count
       - IF (txt REGEXP '[[:space:]]$', 1, 0) -- Exclude whitespace at the end from count
       AS `word count`
FROM tbl;

1

MySQL 8.0现在提供了一个不错的REGEXP_REPLACE函数,使得这个过程更加简单:

SQL

SELECT -- Count the number of gaps between words
       CHAR_LENGTH(txt) -
           CHAR_LENGTH(REGEXP_REPLACE(
               txt,
               '[[:space:]]([[:space:]]*)', -- A chunk of one or more whitespace characters
               '$1')) -- Discard the first whitespace character and retain the rest
           + 1 -- The word count is 1 more than the number of gaps between words
           - IF (txt REGEXP '^[[:space:]]', 1, 0) -- Exclude whitespace at the start from count
           - IF (txt REGEXP '[[:space:]]$', 1, 0) -- Exclude whitespace at the end from count
           AS `Word count`
FROM tbl;

演示

DB-Fiddle 在线演示


0

答案是否定的,你不能在MySQL中拥有相同的行为。

但我建议你查看一下关于这个主题的早期问题,其中链接到一个UDF,据说可以启用部分此功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接