Postgres正则表达式子字符串或正则表达式匹配的实际例子
问题描述:
我一直在试图找出以下几天。请帮助Postgres正则表达式子字符串或正则表达式匹配的实际例子
PostgreSQL表:位置
Id State
--------------------
1 New York
2 Texas
输入='问候从得克萨斯到所有牛仔的
输出:含德州
SELECT id, state FROM locations WHERE state ~* substring(input from state)
答
1.
select * from locations where 'Greetings from Texas to all Cowboys' ~ State;
种
2.
select * from locations where State = any(string_to_array('Greetings from Texas to all Cowboys',' '));
两种方法上面都有一些circumstances.But一些问题,我想知道他们是否适合你。
3.
select * from locations where 'reetings from Texas to all Cowboys' ~* ('\\m' || state || '\\M');
最后一个方法会比较好。
答
行的搜索词是不一种模式。试试这个:
select * from locations where 'Hello from Texas!' like '%' || state || '%';
或本:
select * from locations where 'Hello from Texas!' ~* ('.*' || state || '.*');
如果你想的Posix正则表达式的
。
例子:
# create table locations(id integer, state text);
CREATE TABLE
# insert into locations values (1,'New York'),(2,'Texas') ;
INSERT 0 2
# select * from locations where 'Hello from Texas!' like '%' || state || '%';
id | state
----+-------
2 | Texas
(1 row)
# select * from locations where 'Hello from Texas!' ~* ('.*' || state || '.*');
id | state
----+-------
2 | Texas
(1 row)
# select * from locations where 'Greetings from you ex' like '%' || state || '%';
id | state
----+-------
(0 rows)
# select * from locations where 'Greetings from your ex' ~* ('.*' || state || '.*');
id | state
----+-------
(0 rows)
这需要一些细化或当然,如果你需要检测单词边界:
# select * from locations where 'fakulos greekos metexas' ~* ('.*' || state || '.*');
id | state
----+-------
2 | Texas
如果你有正则表达式,元字符(请参阅为列表中的PostgreSQL的文档)在你的搜索词中,那么你可能需要先引用他们。这看起来有点怪异,但是这是永远逃避的样子:
select regexp_replace('Dont mess (with) Texas, The Lone *',E'([\(\)\*])',E'\\\\\\1','g');
的([\(\)\*])
是要转义字符的列表。
但是,如果你从未需要在你的搜索词的正则表达式,那么它可能是更容易使用一个简单的字符串搜索类似strpos()函数:
select strpos('Dont mess (with) Texas','Texas')>0;
?column?
--------
t
select strpos('Dont mess (with) Texas','Mars')>0;
?column?
--------
f
您可以使用upper()
,如果你想不区分大小写的比较
select strpos(upper('Dont mess (with) Texas'),upper('teXas'))>0;
?column?
--------
t
答
我想看看全文搜索:
SELECT
id,
state
FROM
locations
WHERE
to_tsvector('english', 'Greetings from Texas to all Cowboys') @@ plainto_tsquery('english', state);
标准可作为8.3版本,在旧版本,你必须于contrib安装安装tsearch2。
http://www.postgresql.org/docs/current/interactive/textsearch.html
谢谢你们。它在一张小桌子上完美运作。但不是在包含1百万个位置的巨大桌子上。我认为,这是索引问题 感谢您的快速反应 – Joey 2010-08-04 09:10:20
如果你想这个快速的大表,那么你需要特殊的索引和其他魔法。请参阅http://www.postgresql.org/docs/8.4/static/textsearch.html如何快速进行索引全文搜索。 – 2010-08-04 09:12:28
我发现了为什么我有一个问题。 colunm状态的某些行有一些括号。 从状态如'%(%')返回与行排列的位置的状态选择状态 如何在状态 – Joey 2010-08-04 11:06:36