如何在 mysql 查询中匹配正则表达式


How match regex in mysql query?

我在mysql/postgresql数据库中有content字段(我正在考虑为项目选择哪一个)。 2 行示例:

row1: lorem1 <p>author: ABC</p> ipsum author dollar not text
row2: lorem2 author: ipsum author dollar not text

网页中的用户可以在输入字段中输入who,并且必须找到正则表达式<p>{who}: (.*?)</p>。如果用户输入 $who = 'author' ,则结果将仅从 row1 ABC。怎么做?

它将是这样的: SELECT * FROM table WHERE content LIKE '/<p>{$who}: (.*?)<'/p>/s'

在Postgres中,您可以使用regexp_replace()

示例数据:

create table example (id int, str text);
insert into example values
(1, 'lorem1 <p>author: ABC</p> ipsum author dollar not text'),
(2, 'lorem2 author: ipsum author dollar not text');

查询:

select id, trim(r) result
from 
    example, 
    regexp_replace(str, '^.*?<p>author:(.*?)</p>.*$', ''1') r
where r <> str;
 id | result 
----+--------
  1 | ABC
(1 row)