Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to groups in a MySQL regex?

Tags:

regex

mysql

How to reference to a group using a regex in MySQL? I tried:

REGEXP '^(.)\1$' 

but it does not work. How to do this?

like image 277
The Mask Avatar asked Aug 14 '11 16:08

The Mask


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What is grouping and capturing in regex?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

What is first capturing group in regex?

First group matches abc. Escaped parentheses group the regex between them. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex.


1 Answers

(Old question, but top search result)

For MySQL 8:

SELECT REGEXP_REPLACE('stackoverflow','(.{5})(.*)','$2$1'); -- "overflowstack" 

You can create capture groups with (), and you can refer to them using $1, $2, etc.

For MariaDB, capturing is done in REGEXP_REPLACE with \\1, \\2, etc. respectively.

like image 67
okdewit Avatar answered Sep 18 '22 13:09

okdewit