Reputation: 634
I have the fallowing string ' this is my string '
is it possible to remove all the white spaces from the beginning and the end and just have one space between words.
To select all spaces I've used:
SELECT regexp_replace(' this is my string ', '[ ]{2,}', '', 'g');
The problem with that is the two spaces between words.
Upvotes: 1
Views: 146
Reputation: 784948
You can use:
SELECT regexp_replace(' this is my string ', '^ +| +$| +(?= )', '', 'g');
This will remove all spaces from:
Explanation:
^ +| +$
matches spaces at beginning or at end of the string+(?= )
is a positive lookahead, that matches 1 or more spaces ONLY if it is followed by at least a spaceUpvotes: 3
Reputation: 174696
Use anchors.
SELECT regexp_replace(' this is my string ', '^ +| +$|( ) +', '\1', 'g');
^ +
Matches all the leading one or more spaces.|
OR<space>+$
Matches all the trailing spaces.|
OR (ie, from the remianing string)( ) +
Capture the first space and match all the following spaces.Upvotes: 3
Reputation: 338148
SELECT
trim(both ' ' from regexp_replace(' this is my string ', ' +', ' ', 'g'));
Upvotes: 2