7

I need to SELECT only alpha characters FROM a row though I'm having trouble with the expression. I've tried:

SELECT id, regexp_replace(_column_name_, '0123456789', '') AS _column_alias_
FROM _table_name_;

I know the general gist would only replace numbers however the column only contains alphanumeric characters to begin with.

So if _column_name_ contains a value a1b2c3 how do I make PostgreSQL return the string abc?

0

3 Answers 3

8

The fastest expression to eliminate all digits from a string is with a plain translate():

SELECT translate(col,'0123456789','') AS col_without_digits
FROM   tbl;

Regular expressions are powerful and versatile but more expensive.

Your mistake was the missing "global" switch as 4th parameter, as pointed out by @Ben. While using regular expressions, you can also use the class shorthand \d:

SELECT regexp_replace(col, '\d', '', 'g') AS col_without_digits
FROM   tbl;
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, now I have to benchmark the two answers. Looking in to dba.stackexchange.com/questions/42012/…. The other answer works of course so working on it. :-)
6.076 ms versus 1.773 ms, it definitely was faster and I wonder how much more so when I get to switch my laptop to an SSD. I'll up-vote Ben and accept yours.
@John: I have been running many benchmarks over the past years. The outcome is as expected.
Not that I doubted you though I haven't benchmarked anything in PostgreSQL until today and now I've got two more updates for my MySQL/PostgreSQL cross-reference. :-)
4

The syntax is regexp_replace(string text, pattern text, replacement text [, flags text]), using 'g' for flags makes the replacement global:

SELECT id, regexp_replace(_column_name_,'[0-9]','','g') AS _column_alias_
FROM _table_name_;

1 Comment

Thanks! It does work though Erwin's translate() was faster, up-voted at least.
3

If you want to remove also punctuation and everything that is not an alpha:

SELECT id, regexp_replace(_column_name_, '[^a-zA-Z]', '', 'g') AS _column_alias_
FROM _table_name_;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.