【问题标题】:Why's this postgres regexp_match giving me null instead of the regex groups?为什么这个 postgres regexp_match 给我 null 而不是正则表达式组?
【发布时间】:2020-02-15 23:35:30
【问题描述】:

这个:

select regexp_matches('test text user:testuser,anotheruser hashtag:peach,phone,milk site:youtube.com,twitter.com flair:????bobby????', '^.*?(?=\s+[^:\s]+:)|([^:\s]+):([^:\s]+)','gi');

只给我一个组匹配和一个 NULL 行:

regexp_matches  
-----------------
 {NULL,NULL}
 {flair,????bobby????}

我在这里测试时效果很好:

https://regex101.com/r/AxsatL/3

我做错了什么?

【问题讨论】:

  • 您做错了什么是假设所有正则表达式引擎都是相同的。它们是不是。使用将要运行的引擎测试并构建您的表达式。在这种情况下,Postgres;请参阅 Postgres Pattern Matching 文档。

标签: regex postgresql regex-group postgres-9.6


【解决方案1】:

你可以使用

'^(?:(?!\s+[^:\s]+:).)*|[^:\s]+:[^:\s]+'

这里的重点是让所有量词保持贪婪并删除所有捕获括号。

^(?:(?!\s+[^:\s]+:).)* 部分将匹配 - 从字符串的开头 - 任何不以下列模式序列开头的字符,0 次或多次出现:1+ 空格,1+ : 以外的字符和空格,然后是 :

Online test:

select regexp_matches(
    'test text user:testuser,anotheruser hashtag:peach,phone,milk site:youtube.com,twitter.com flair:?bobby?',
    '^(?:(?!\s+[^:\s]+:).)*|[^:\s]+:[^:\s]+',
    'gi'
);

结果:

【讨论】:

  • 当我在一个真正的 postgres 数据库上测试它时,它给了我一个有点不同的结果: {"test text",NULL,NULL} {NULL,user,"testuser,anotheruser"} {NULL, hashtag,"peach,phone,milk"} {NULL,site,"youtube.com,twitter.com"} {NULL,flair,?bobby?}
  • @PranoyC 删除捕获括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2012-01-26
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多