Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract only 5 digit number from a string using REGEXP sql

I need to extract only 5 digit numbers from a string using REGEXP sql in postgresql or redshift DB

For example,

f 34 123 54321 123456

above string should return

54321

I am able to get only numbers from string but not only 5 digit number

select REGEXP_REPLACE('f 34 123 54321 123456', '[^0-9]') five_digit_number
--returns 3412354321123456
like image 556
logan Avatar asked Oct 31 '25 11:10

logan


1 Answers

Use regexp_matches.

select regexp_matches('f 34 123 54321 123456','\y\d{5}\y','g')

Specifying 'g' flag gives you all the matches in case there is more than one 5 digit occurrence in the string.

\y specifies a word boundary.

For Redshift, you can use regexp_substr.

select REGEXP_SUBSTR('f 34 123 54321 123456', '(^|[^[:word:]]|[[:space:]])\\d{5}([^[:word:]]|[[:space:]]|$)')
like image 61
Vamsi Prabhala Avatar answered Nov 03 '25 02:11

Vamsi Prabhala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!