【问题标题】:PostgreSQL Regex Word Boundaries?PostgreSQL 正则表达式词边界?
【发布时间】:2010-09-29 20:41:33
【问题描述】:

PostgreSQL 是否支持\b

我正在尝试 \bAB\b 但它不匹配任何内容,而 (\W|^)AB(\W|$) 匹配。这两种表达方式本质上是一样的,不是吗?

【问题讨论】:

    标签: regex postgresql word-boundary


    【解决方案1】:

    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

    还有[[:<:]][[:>:]],它们匹配单词的开头和结尾。来自the manual

    括号表达式有两种特殊情况:括号表达式[[:<:]][[:>:]]是约束,分别匹配单词开头和结尾的空字符串。一个单词被定义为一个单词字符序列,它既不在单词字符的前面也不在其后面。单词字符是 alnum 字符(由 ctype 定义)或下划线。这是一个扩展,与 POSIX 1003.2 兼容但未指定,在旨在移植到其他系统的软件中应谨慎使用。下面描述的约束转义通常是可取的(它们不再是标准的,但肯定更容易键入)。

    【讨论】:

      【解决方案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'; 应该可以工作了。

      【讨论】:

      • 我使用 postgres 9.3.10 和 value ~* '\yAB\y' 工作得很好。你的笔记是 9.2 专用的吗?
      • 同上,回复:postgres 10.2:... where synonyms ~* '\ya1b\y'; 有效;双反斜杠版本'\\ya1b\\y' 不起作用。
      【解决方案3】:

      文本中的精确单词搜索:

      我遇到了以下问题。

      我想搜索标题中包含“cto”作为确切单词的所有联系人,但在结果中得到标题中包含“director”的结果,我正在使用以下查询

      select * from contacts where title ilike '%cto%';
      

      我还尝试使用通配符周围的空白作为“% cto %”,它与包含“cto”的文本匹配,得到类似“vp、cto 和 manger”的结果,但没有准确标题为“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”。谢谢,因为您的想法帮助我找到了这个解决方案:stackoverflow.com/questions/18080104/…
      猜你喜欢
      • 2011-04-14
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多