Home > Database > Mysql Tutorial > How to Reference Capture Groups in Regular Expressions in MySQL?

How to Reference Capture Groups in Regular Expressions in MySQL?

DDD
Release: 2024-11-03 15:00:30
Original
973 people have browsed it

How to Reference Capture Groups in Regular Expressions in MySQL?

Regex Capture Group Referencing in MySQL

In MySQL, referencing a capture group within a regular expression can be achieved using the following method:

Syntax:

REGEXP_REPLACE(string, pattern, replacement)
Copy after login

For MySQL 8:

Capture groups can be created using parentheses (). To refer to a capture group, use $1, $2, and so on.

<code class="sql">SELECT REGEXP_REPLACE('stackoverflow','(.{5})(.*)','');
-- Output: "overflowstack"</code>
Copy after login

For MariaDB:

Capture groups in MariaDB are managed differently. Backreferences use \1, \2, and so forth.

<code class="sql">SELECT REGEXP_REPLACE('stackoverflow','(.{5})(.*)','\2\1');
-- Output: "overflowstack"</code>
Copy after login

Example:

The regular expression ^(.)1$ checks if there are two identical characters at the start of the string, but this syntax will not work in MySQL. Instead, use the following:

<code class="sql">SELECT REGEXP_REPLACE('aabbcc','^(.)(.)$','');
-- Output: "b"</code>
Copy after login

This regex matches the first two characters of the string (a and a) as two capture groups and retrieves the second character (b).

The above is the detailed content of How to Reference Capture Groups in Regular Expressions in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template