Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL regular expression

I have a string like 'ABC3245-bG1353BcvG34'. I need to remove the hyphen including all the letters after hyphen.

so the above string should be ABC3245135334

I tried the below code:

select substring('ABC3245-bG1353BcvG34' from 1 for (position('-' in 'ABC3245-bG1353BcvG34')-1))||regexp_replace(substring('ABC3245-bG1353BcvG34' from (position('-' in 'ABC3245-bG1353BcvG34') +1) for length('ABC3245-bG1353BcvG34')),'[a-zA-Z]','')

but not able to remove letters after the hyphen.

like image 527
Stu Avatar asked Dec 09 '25 05:12

Stu


2 Answers

I need to remove the hyphen including all the letters after hyphen.

so the above string (ABC3245-bG1353BcvG34) should be ABC3245135334

This suggests that all numbers should remain after the hyphen (in their original order). If that's what you want, you cannot do this with a single regex. Assuming you can have only 1 hyphen in your input:

SELECT substring(input.value from '^[^-]*') ||
       regexp_replace(substring(input.value from '[^-]*$'), '\D+', '', 'g')
FROM (SELECT 'ABC3245-bG1353BcvG34'::text AS value) AS input

If you can have multiple hyphens in your input, please define how to handle characters between hyphens.

like image 133
pozs Avatar answered Dec 11 '25 22:12

pozs


Fixed version

SELECT a[1] || regexp_replace(a[2], '\D', '', 'g')
FROM   string_to_array('ABC3245-bG1353BcvG34', '-') AS a

Or, more convenient to deal with a set (like a table):

SELECT split_part(str, '-', 1)
    || regexp_replace(split_part(str, '-', 2), '\D', '', 'g')
FROM  (SELECT 'ABC3245-bG1353BcvG34'::text AS str) tbl

Removes all non-digits after the hyphen. (Assuming there is only one hyphen.) Result:

ABC3245135334

First version

Missed that OP wants to remove all letters after -.

SELECT regexp_replace('ABC3245-bG1353BcvG34', '-\D*', '')

Result:

ABC32451353BcvG34

Regex explained:

- .. literal hyphen -
\D .. class shorthand for "non-digits".
* .. 0 or more times

Removes the first hyphen and everything that follows until the first digit.

like image 29
Erwin Brandstetter Avatar answered Dec 11 '25 22:12

Erwin Brandstetter



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!