Come contare le parole in MySQL / espressione regolare sostituto?
-
20-09-2019 - |
Domanda
Come posso, in una query MySQL, avere lo stesso comportamento come la funzione Regex.Replace (ad esempio in .NET / C #)?
ho bisogno perché, come molte persone, vorrei contare il numero di parole in un campo. Tuttavia, non sono soddisfatti della risposta che segue (dato più volte su quel sito):
SELECT LENGTH(name) - LENGTH(REPLACE(name, ' ', '') +1 FROM table
Perché non dà buoni risultati quando ci sono più che uno spazio tra due parole.
A proposito, penso che la funzione Regex.Replace può essere interessante in modo da tutte le buone idee sono benvenute!
Soluzione
C'è REGEXP_REPLACE disponibile come MySQL funzioni definite dall'utente .
conteggio Word: Se è possibile controllare i dati che vanno nel database, è possibile rimuovere doppio spazio prima inserto. Anche se si deve accedere il conteggio delle parole spesso, è possibile calcolare una volta nel codice e memorizzare il conteggio nel database.
Altri suggerimenti
UPDATE: Ora hanno aggiunto una risposta separata per MySQL 8.0+ , che dovrebbe essere usato di preferenza. (Portati a questa risposta in caso di essere constrainted di utilizzare una versione precedente.)
Quasi un duplicato di questa domanda ma questa risposta affronterà il caso d'uso di contare le parole in base alla versione avanzata del regolare sostituto personalizzato espressione da questo post del blog .
Demo
Per il testo di esempio, questo dà un conteggio di 61 - lo stesso di tutti i contatori di parola in linea che ho provato (ad esempio https :. //wordcounter.net/ )
SQL (escluso il codice funzione per brevità) :
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 8.0 ora offre un REGEXP_REPLACE funzione, che rende questo molto più semplice:
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;
Demo