首页 > 解决方案 > 整个短语的Postgres位置功能?字符串搜索

问题描述

有没有办法使用位置或其他函数在字段中查找字符串但不让它成为另一个单词的一部分?例如,如果我正在寻找带有位置的“长凳”这个词,我会做这样的事情

 POSITION('bench' IN products)

产品列看起来像这样

 **Products**
 tool bench
 benchpress
 park bench
 benchmark
 bench heater
 utility bench tool

我只想匹配 bench 不是另一个单词的一部分的行(不想匹配 benchpress 或 benchmark)。谢谢

标签: sqlpostgresql

解决方案


使用\y正则表达式(单词边界匹配器):

with t(word) as (values
  ('tool bench'),
  ('benchpress'),
  ('park bench'),
  ('benchmark'),
  ('bench heater'),
  ('utility bench tool')
)
select *
from t
where word ~ '\ybench\y'

Dbfiddle在这里。


推荐阅读