Regex 从PostgreSQL中的字段中提取数字

Regex 从PostgreSQL中的字段中提取数字,regex,postgresql,conditional,case,regexp-replace,Regex,Postgresql,Conditional,Case,Regexp Replace,在Postgres 8.4中,我有一个表,其列为po_number,类型为varchar。它存储带有一些特殊字符的字母数字值。我想忽略字符[/alpha/?/$/encoding/][/code>,并检查列是否包含数字。如果它是一个数字,那么它需要类型转换为数字或传递null,因为我的输出字段po_number\u new是一个数字字段 下面是一个例子: 我厌倦了这种说法: select (case when regexp_replace(po_number,'[^\w],.-+\?/'

在Postgres 8.4中,我有一个表,其列为
po_number
,类型为
varchar
。它存储带有一些特殊字符的字母数字值。我想忽略字符
[/alpha/?/$/encoding/][/code>,并检查列是否包含数字。如果它是一个数字,那么它需要类型转换为数字或传递null,因为我的输出字段
po_number\u new
是一个数字字段

下面是一个例子:

我厌倦了这种说法:

select 
(case when  regexp_replace(po_number,'[^\w],.-+\?/','') then po_number::numeric
else null
end) as po_number_new from test
但我在显式强制转换时出错:


我想你想要这样的东西:

select (case when regexp_replace(po_number, '[^\w],.-+\?/', '') ~ '^[0-9]+$'
             then regexp_replace(po_number, '[^\w],.-+\?/', '')::numeric
        end) as po_number_new 
from test;
也就是说,替换后需要对字符串进行转换


注意:这假设“数字”只是一个数字串。

我用来确定
po_number
字段是否包含数字的逻辑是,当尝试删除数字时,其长度应该减少

如果是,则应从
采购订单编号
列中删除所有非数字数字(
[^\d]
)。否则,应返回
NULL

select case when char_length(regexp_replace(po_number, '\d', '', 'g')) < char_length(po_number)
            then regexp_replace(po_number, '[^0-9]', '', 'g')
            else null
       end as po_number_new
from test
当字符长度(regexp\u替换(po\u编号,'\d',''g'))小于字符长度(po\u编号)时选择大小写
然后用regexp替换(采购订单编号“[^0-9]”,“'g')
否则无效
结束时为采购订单编号\u新
从测试
简单地说:

SELECT NULLIF(regexp_replace(po_number, '\D','','g'), '')::numeric AS result
FROM   tbl;
\D
是“非数字”的课堂速记。
您需要第四个参数
'g'
(用于“全局”)来替换所有出现的情况。

但为什么要考8.4级

考虑过时版本的陷阱:


您能解释一下regexp
,.-+
?这是什么意思?@Abelisto我想它们应该在括号内,虽然我现在不在Postgre前面测试它。使用上面的方法后,我只得到空值。。。相反,我需要每个记录中的数字,如果itI中没有数字,则需要为空。在尝试之后,我收到一个SQL错误[42883]this@user1538020错误是由您使用Postgres 8.x引起的,它没有
length
函数。我更新为使用
char_length
,现在应该可以使用了;我现在使用PostgreSQL 95.2,用Visual C++编译生成1800, 64位。还是有错误。我发布了图像错误。@user1538020:Asides:您得到的错误是由于键入错误:
regex\u replace
regexp\u replace
。在第8.4页中有一个
length()
函数。@Tim Biegeleisen:当字符长度(regexp\u replace(po\u编号,'\d',''g'))