如何统计 MySQL/正则表达式替换器中的单词数?
-
20-09-2019 - |
题
如何在 MySQL 查询中具有与 Regex.Replace 函数相同的行为(例如在 .NET/C# 中)?
我需要它,因为和很多人一样,我想计算一个字段中的单词数。但是,我对以下答案不满意(在该网站上多次给出):
SELECT LENGTH(name) - LENGTH(REPLACE(name, ' ', '') +1 FROM table
因为当两个单词之间的空格超过一个时,它不会给出好的结果。
顺便说一句,我认为 Regex.Replace 函数可能很有趣,所以欢迎所有好主意!
解决方案
有REGEXP_REPLACE可作为 MySQL的用户定义的函数的。
字计数:如果你可以控制数据进入数据库,你可以插入之前删除双重空白。此外,如果你需要访问这个词经常算,可以一次在你的代码计算它和将计在数据库中。
其他提示
更新:现已添加 MySQL 8.0+ 的单独答案, ,应优先使用。(保留这个答案,以防仅限于使用早期版本。)
几乎是重复的 这个问题 但这个答案将解决基于自定义正则表达式替换器的高级版本的单词计数的用例 这篇博文.
演示
对于示例文本,计数为 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;
答案是否定的,你不能在MySQL中相同的行为。
但我建议您签这早些时候问题一>在其上链接到UDF,理应使得一些这种功能的主题。
8.0的MySQL现在提供了一种体面 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;
<强>演示强>
不隶属于 StackOverflow