代码之家  ›  专栏  ›  技术社区  ›  pierroz

如何计算mysql/regular expression replacer中的单词?

  •  16
  • pierroz  · 技术社区  · 15 年前

    在MySQL查询中,我如何具有与regex.replace函数相同的行为(例如在.net/c中)?

    我需要它是因为,和许多人一样,我想计算一个字段中的单词数。但是,我对以下答案不满意(在该网站上给出了几次):

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

    因为当两个词之间有一个以上的空格时,它不会产生好的效果。

    顺便说一下,我认为regex.replace函数可能很有趣,所以欢迎所有的好主意!

    4 回复  |  直到 7 年前
        1
  •  17
  •   laalto    15 年前

    有regexp ou replace可用作 MySQL user-defined functions .

    字数统计:如果你能控制数据进入数据库,你可以在插入前删除两个空格。另外,如果您必须经常访问单词计数,您可以在代码中计算一次,并将该计数存储在数据库中。

        2
  •  1
  •   Steve Chambers    7 年前

    更新:已添加 a separate answer for MySQL 8.0+ ,应优先使用。(保留此答案以防被限制使用早期版本。)

    几乎是 this question 但是,这个答案将解决基于高级版本的自定义正则表达式替换器来计算单词的用例。 this blog post .

    演示

    Rextester online demo

    对于示例文本,这给出了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;
    
        3
  •  0
  •   Community CDub    8 年前

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

    但是我建议你早点结账 question 关于链接到一个假定可以实现某些功能的UDF的主题。

        4
  •  0
  •   Steve Chambers    7 年前

    MySQL8.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 online demo