两个模式之间的Postgres regexp_matches

时间:2018-12-12 16:33:03

标签: regex postgresql

我试图像Postgres 9.4中那样拆分表达式: “某些文本123_good_345和其他文本123_some_invalid和222_work ok_333停止。”

使用模式:(\d+\_.*\_\d+\D)+? 结果是:

"123_good_345"
"123_some_invalid and 222_work ok_333"

但是我需要

"123_good_345"
"222_work ok_333"

请注意,忽略“ 123_some_invalid”

请帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用

\d+_(?:(?!\d_).)*_\d+

请参见regex demo。或者,如果\d+__\d+之间没有数字,请使用

\d+_\D+_\d+

请参见this regex demo

详细信息

  • \d+-1个或更多数字 -_-下划线
  • (?:(?!\d_).)*-不以数字+ _字符序列开头的任意字符,最多0个或多个重复,并且不以数字开头。
  • \D+-除数字外的任何1个以上字符
  • _-下划线
  • \d+-1个以上的数字。

请参见PostgreSQL demo

SELECT unnest(regexp_matches('some text 123_good_345 and other text 123_some_invalid and 222_work ok_333 stop.', '\d+_(?:(?!\d_).)*_\d+', 'g'));

SELECT unnest(regexp_matches('some text 123_good_345 and other text 123_some_invalid and 222_work ok_333 stop.', '\d+_\D+_\d+', 'g'));

enter image description here