如何在 MySQL 查询中使用正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18780194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:49:45  来源:igfitidea点击:

How to regex in a MySQL query

mysqlsqlregexinnodb

提问by zzlalani

I have a simple task where I need to search a record starting with string characters and a single digit after them. What I'm trying is this

我有一个简单的任务,我需要搜索以字符串字符开头并在它们后面有一个数字的记录。我正在尝试的是这个

SELECT trecord FROM `tbl` WHERE (trecord LIKE 'ALA[d]%')

And

SELECT trecord FROM `tbl` WHERE (trecord LIKE 'ALA[0-9]%')

But both of the queries always return a nullrecord

但是这两个查询总是返回一条null记录

trecord
-------
null

Where as if I execute the following query

好像我执行以下查询

SELECT trecord FROM `tbl` WHERE (trecord LIKE 'ALA%')

it returns

它返回

trecord
-------
ALA0000
ALA0001
ALA0002

It means that I have records that starts with ALA and a digit after it,

这意味着我有以 ALA 开头和后面的数字的记录,

EDIT

编辑

I'm doing it using PHP MySQL and innodb engine to be specific.

我正在使用 PHP MySQL 和 innodb 引擎来进行具体操作。

回答by Wietze314

I think you can use REGEXPinstead of LIKE

我认为您可以使用REGEXP而不是 LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

回答by Andrew

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

就我而言(Oracle),它是WHERE REGEXP_LIKE(column, 'regex.*'). 见这里

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

SQL函数

描述


REGEXP_LIKE

此函数在字符列中搜索模式。在查询的 WHERE 子句中使用此函数可返回与您指定的正则表达式匹配的行。

...

REGEXP_REPLACE

此函数在字符列中搜索模式,并用您指定的模式替换该模式的每次出现。

...

REGEXP_INSTR

此函数在字符串中搜索给定出现的正则表达式模式。您可以指定要查找的事件以及要搜索的起始位置。此函数返回一个整数,指示在字符串中找到匹配项的位置。

...

REGEXP_SUBSTR

此函数返回与您指定的正则表达式模式匹配的实际子字符串。

(Of course, REGEXP_LIKE only matches queries containingthe search string, so if you want a complete match, you'll have to use '^$'for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

(当然, REGEXP_LIKE 只匹配包含搜索字符串的查询,所以如果你想要一个完整的匹配,你必须使用'^$'开头 ( ^) 和结尾 ( $) 匹配,例如:'^regex.*$'。)