Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return numbers in string:postgresql

I have the string: I am 10 years old with 500 friends. I want to return 10 and 500 but when I executed the query below and it returned empty:

SELECT
REGEXP_MATCHES('I have the string: I am 10 years old with 500  friends',
                '-?\\d+','g');
like image 318
Shawn12 Avatar asked Jul 05 '26 13:07

Shawn12


1 Answers

The problem is with the double anti-slash. While some databases require regex character classes to be escaped, Postgres expects just one anti-slash.

So:

select regexp_matches(
    'I have the string: I am 10 years old with 500 friends',
    '-?\d+',
    'g'
);

'-?' is not sensible for your example string. I left it as is in case you want to accomodate for possible negative numbers.

Demo on DB Fiddle

like image 139
GMB Avatar answered Jul 07 '26 04:07

GMB



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!