2014-02-21 31 views
6

我在namecontacts表內類似這樣的幾個值:從柱只返回數值 - PostgreSQL的

test 3100509 DEMO NPS

我只想返回從name數字一塊的每個值。

我嘗試這樣做:

select substring(name FROM '^[0-9]+|.*') from contacts

但是,這並不這樣做。

有關如何從返回的值中除去不是數字的所有字符的想法?

回答

10

試試這個:

select substring(name FROM '[0-9]+') from contacts 
9

select regexp_replace(name , '[^0-9]*', '', 'g') from contacts;

這應該這樣做。即使名稱中有多個數字序列,它也可以工作。

例子:

create table contacts(id int, name varchar(200)); 

insert into contacts(id, name) values(1, 'abc 123 cde 555 mmm 999'); 

select regexp_replace(name , '[^0-9]*', '', 'g') from contacts; 
+0

+1,甚至還可能有[RegExp類速記(HTTP:// (名稱,'\ D','','g')FROM聯繫人; ' –

0

如果你想提取帶小數點的數值比使用

select NULLIF(regexp_replace(name, '[^0-9.]*','','g'), '')::numeric from contacts