16

I have several values in my name column within the contacts table similar to this one:

test 3100509 DEMO NPS

I want to return only the numeric piece of each value from name.

I tried this:

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

But that doesn't do it.

Any thoughts on how to strip all characters that are not numeric from the returned values?

3 Answers 3

18

Try this :

select substring(name FROM '[0-9]+') from contacts
Sign up to request clarification or add additional context in comments.

1 Comment

not the best answer. if I put: select substring('998343913-15' from '[0-9]+') I get 998343913 and not 99834391315
14

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

This should do it. It will work even if you have more than one numeric sequences in the name.

Example:

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;

1 Comment

+1 And maybe even with a regexp class shorthand: SELECT regexp_replace(name, '\D', '', 'g') FROM contacts;
3

If you want to extract the numeric values with decimal point than use this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.