PostgreSQL支持\b
吗?
我正在尝试\bAB\b
,但它并未匹配任何内容,而(\W|^)AB(\W|$)
却可以。这两个表达式本质上是相同的,不是吗?
PostgreSQL支持\b
吗?
我正在尝试\bAB\b
,但它并未匹配任何内容,而(\W|^)AB(\W|$)
却可以。这两个表达式本质上是相同的,不是吗?
PostgreSQL 使用 \m
、\M
、\y
和 \Y
作为单词边界:
\m matches only at the beginning of a word
\M matches only at the end of a word
\y matches only at the beginning or end of a word
\Y matches only at a point that is not the beginning or end of a word
请参阅手册中的Regular Expression Constraint Escapes。[[:<:]]
和[[:>:]]
,它们匹配单词的开头和结尾。来自该手册:[[:<:]]
和[[:>:]]
是约束条件,分别匹配单词的开头和结尾的空字符串。单词被定义为不以单词字符为前导或后继的单词字符序列。单词字符是alnum字符(由ctype定义)或下划线。这是一个扩展,与 POSIX 1003.2 兼容,应在旨在可移植到其他系统的软件中谨慎使用。下面描述的约束转义通常更可取(它们并不更标准,但肯定更容易输入)。一个简单的例子
select * from table_name where column ~* '\yAB\y';
这将匹配 AB
ab
ab - text
text ab
text AB
text-ab-text
text AB text
...
但是您必须使用:
select * from sometable where name ~* '\\yAB\\y';
如果你的standard_conforming_strings
标志设置为OFF
,请注意双斜杠。
你可以手动设置它:
set standard_conforming_strings=on;
那么:select * from table_name where column ~* '\yAB\y';
应该可以正常工作。
文本中的精确词搜索:
我遇到了以下问题。
我想要搜索所有标题中包含“cto”精确单词的联系人,但结果中出现了标题中包含“director”的结果。 我使用以下查询:
select * from contacts where title ilike '%cto%';
select * from contacts where title ~* '\\ycto\\y';
~ Matches regular expression, case sensitive
~* Matches regular expression, case insensitive
phrase ILIKE '% cto %'
时,您只需要在短语周围添加空格:' ' || phrase || ' ' ILIKE '% cto %'
。这适用于标题为“cto”。感谢您的想法,帮助我找到了这个解决方案:https://stackoverflow.com/questions/18080104/ilike-match-word-boundaries-postgresql-9/47120301#47120301 - Stepan Zakharov
... where synonyms ~* '\ya1b\y';
是可以工作的;双反斜杠版本'\\ya1b\\y'
则无法工作。 - Victoria Stuart