Postgresql:在给定子字符串之前提取数字

时间:2016-05-23 12:37:28

标签: postgresql substring

我想创建变量:在$

之前提取数字的数字
Name      | Number
abc1/12 $ | 12
12av 12$  | 12
114$-bgv  | 114

我有一个问题:

select Name, substring(Name FROM '%#"[0-9]+#"$%' FOR '#') as Number
from table;

但它返回:

Name      | Number
abc1/12 $ | 
12av 12$  | 2
114$-bgv  | 4

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用regexp_matches()

select
  (regexp_matches(Name,  '^(.*[^\d]+){0,1}(\d+)\$'))[2] as Number
from (
  select 'abc1/12$' as Name
  union select '12av 12$'
  union select 'bgv-114$'
  union select '124$'
) t

substring()

select
  coalesce(substring(Name FROM '.*[^\d]+(\d+)\$'), '') ||
  coalesce(substring(Name FROM '^(\d+)\$'), '') as Number
from (
  select 'abc1/12$' as Name
  union select '12av 12$'
  union select 'bgv-114$'
  union select '124$'
) t