请帮助为这种情况定义Postgres regexp:
我有字符串字段:
union all select 'AbC-345776-2345' /*comment*/ union all select 'Fgr-sdf344-111a' /*BN34*/ some text union all select 'sss-sdf34-123' /*some text*/ some text
以下是select语句中的相同文本以方便使用:
select 'union all select ''AbC-345776-2345'' /*comment*/ union all select ''Fgr-sdf344-111a'' /*BN34*/ some text union all select ''sss-sdf34-123'' /*some text*/ some text' as str
我需要从这个混乱中获得"…"中的纯文本值并将其选择为如下分隔行:
AbC-345776-2345
Fgr-sdf344-111a
sss-sdf34-123
图案:"前2-3个字母-几个字母和数字-几个字母或数字">
我创建了这个选择,但它包含了所有的评论和";sometext";以及:
select regexp_split_to_table(trim(replace(replace(replace(replace(t1.str,'union all select',''),'from DUAL',''),chr(10),''),'''','') ), E'\s+')
from (select 'union all select ''AbC-345776-2345'' /*comment*/ union all select ''Fgr-sdf344-111a'' /*BN34*/ some text union all select ''sss-sdf34-123'' /*some text*/ some text' as str) t1;
以下操作应该完成:
select (regexp_matches(str, $$'([a-zA-Z]{2,3}-[a-zA-Z0-9]+-[a-zA-Z0-9]+)'$$, 'g'))[1]
from the_table;
给定您的样本数据,它将返回:
regexp_matches
---------------
AbC-345776-2345
Fgr-sdf344-111a
sss-sdf34-123
正则表达式检查您在单引号内指定的模式。通过使用组(...)
,我从结果中排除了单引号。
regexp_matches()
为每个匹配返回一行,其中包含一个匹配数组。但是由于正则表达式只包含一个组,数组的第一个元素就是我们感兴趣的
我使用美元报价来避免转义正则表达式中的单引号
在线示例