0

Let's say I have column of datatype varchar, the column contains values similar to these

'My unique id [john3 UID=123]'
'My unique id [henry2 UID=1234]'
'My unique id [tom2 UID=56]'
'My unique id [jerry25 UID=98765]'

How can I get only the numbers after UID= in the strings using postgresql. for eg in string 'My unique id [john3 UID=123]' I want only 123, similarly in string 'My unique id [jerry25 UID=98765]' I want only 98765 Is there a way in PostgreSQL to do it?

2 Answers 2

3

We can use REGEXP_REPLACE here:

SELECT col, REGEXP_REPLACE(col, '.*\[\w+ UID=(\d+)\].*$', '\1') AS uid
FROM yourTable;

Demo

Edit:

In case a given value might not match the above pattern, in which case you would want to return the entire original value, we can use a CASE expression:

SELECT col,
       CASE WHEN col LIKE '%[%UID=%]%'
            THEN REGEXP_REPLACE(col, '.*\[\w+ UID=(\d+)\].*$', '\1')
            ELSE col END AS uid
FROM yourTable;
Sign up to request clarification or add additional context in comments.

5 Comments

You won't get a better answer than this one ;) +1 However, if you want a "non-regex" solution check this
Thanks Tim, this works for me! Probably I need to go through regex in postgresql
Is there a way to return the value 0 if the REGEXP_REPLACE returns you only string, for example in case of my name is jerry the REGEXP_REPLACE will return my name is jerry instead of that can i return a value 0?
@kannappan I have given you a version which will behave as you expect.
@kannappan you can achieve by checking if the result is a number (if applicable) within a case. check this fiddle
1

You can also use regexp_matches for a shorter regular expression:

select regexp_matches(col, '(?<=UID\=)\d+') from t;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.