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
How to Trim Strings. in PostgreSQL. The trim () function removes specified characters or spaces from a string. You can specify to trim from only the start or end of the string, or trim from both. This is best explained using examples. You can trim "1" from start of the string: select trim(leading '1' from '111hello111'); ltrim ---------- hello111.
TRIM (LEADING FROM string) The following syntax of the TRIM () function removes all spaces from the end of a string. TRIM (TRAILING FROM string) And to remove all spaces at the beginning and ending of a string, you use the following syntax:
PostgreSQL also supports the non-standard syntax of specifying which characters to remove as the last parameter, separated by a comma: Not specifying where to trim from has the same result as "both":
I want to remove all the specials characters, but replace the spaces with an underscore: ABC_DEF_GHI But that removes all the characters, including spaces. Show activity on this post. Do the space-to-underscore replace () first, and your existing expression will do the rest. testdb=# select regexp_replace (replace ('ABC%$!
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With