6

So I have a column with the following values that some times has a number in the beginning

turtle boat
10 banana split
lord Thanos
23 macbook

How to query to remove numbers and the space in front of the numbers, but not the space in the middle of the string?

Intended output:

turtle boat
banana split
lord Thanos
macbook

Query I tried from another question in here:

select regexp_replace(mycolumn, '[^[:alpha:]]', '', 'g')

Problem with this query is that it completely removes all spaces

2 Answers 2

10

You can exclude all characters except of letters and spaces. Additionally, use trim() to remove leading or trailing spaces:

with my_data(mycolumn) as (
values
    ('turtle boat'),
    ('10 banana split'),
    ('lord Thanos'),
    ('23 macbook')
)

select trim(regexp_replace(mycolumn, '[^[:alpha:]\s]', '', 'g'))
from my_data

    btrim     
--------------
 turtle boat
 banana split
 lord Thanos
 macbook
(4 rows)    
Sign up to request clarification or add additional context in comments.

Comments

4

This will remove the leading digits and the space:

select regexp_replace('10 banana split', '^\d+ ', '');

/^\d+[ ]/
 ^ asserts position at start of a line
  \d+ matches a digit (equal to [0-9])
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
     [ ] matches the character ' ' literally (case sensitive)

The g modifier, for 'global', is why in your regex all spaces were removed, as matched as non-alpha characters.

fiddle here

1 Comment

i like stripping the leading number better than stripping the leading not alpha (and not space). either works. addressing the number seems more appropriate because the op wanted to remove a potential leading number.

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.