RustyShackleford
RustyShackleford

Reputation: 3677

How to trim ONLY certain characters from string in Postgresql database?

I have a table in a db that is labeled like so:

TableA:

  ID               ID2    Text
0 64556-546-1    465846    adfadf    
1 64556-546-1    465846    adfadf
2 64556-546-1    465846    adfadf

I want to trim the symbol(-) and digit after the dash only from the first column and only the dash in the second position how would I go about this? so the number will look like 64556-546.

The value will be compared to another in another table, so no need to create another column.

Thank you in advance.

Upvotes: 0

Views: 866

Answers (1)

juju
juju

Reputation: 555

I'd check here;

https://www.postgresql.org/docs/9.1/static/functions-string.html

and do a;

regexp_replace(string text, pattern text, replacement text [, flags text])

So one way to do it (ignoring probable performance issues), would be;

SELECT TRIM(BOTH '-1' FROM regexp_replace(ID, '[-]', '' )) FROM TableA

But you could probably build a better way with a more advanced regex.

Upvotes: 2

Related Questions