Skip to content

Instantly share code, notes, and snippets.

@sfaut
Created April 2, 2023 14:32
Show Gist options
  • Save sfaut/5c96db91b1ed458b93bc9ef7a135e6da to your computer and use it in GitHub Desktop.
Save sfaut/5c96db91b1ed458b93bc9ef7a135e6da to your computer and use it in GitHub Desktop.
This REGEXP_COUNT() MySQL implementation returns the number of times pattern is matched in expression
-- Returns the number of times pattern is matched in expression
-- Author : sfaut <https://github.com/sfaut>
-- Publication date : 2023-04-02
-- Tested with MySQL 8.0.32 (@@sql_mode='ANSI,TRADITIONAL')
DELIMITER ;;
CREATE FUNCTION "REGEXP_COUNT"(expression TEXT, pattern TEXT)
RETURNS INT UNSIGNED
DETERMINISTIC
COMMENT 'Returns the number of times pattern is matched in expression'
BEGIN
DECLARE result INTEGER UNSIGNED DEFAULT 0;
DECLARE last_position INTEGER UNSIGNED DEFAULT 1;
DECLARE expression_length INTEGER UNSIGNED DEFAULT CHAR_LENGTH(expression);
REPEAT
SET last_position = REGEXP_INSTR(expression, pattern, last_position, 1, 1);
IF last_position > 0 THEN
SET result = result + 1;
END IF;
UNTIL last_position = 0 OR last_position > expression_length END REPEAT;
RETURN result;
END;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment