jkshah jkshah - 4 months ago 9
Perl Question

Removing leading, trailing and multiple spaces within a string

I would like to remove all leading and trailing spaces. As well as replace multiple spaces with a single space within a string, so that all words in a string are separated exactly by single space.

I could achieve this using following two iteration of regex and looking for single regex solution.

s/^\s+|\s+$//g
s/\s+/ /g


Sample Input:

word1 word2 word3 word4


Desired Output:

word1 word2 word3 word4


It would be appreciable if you could help me to solve this.

Answer

You can use something like:

s/^\s+|\s+$|\s+(?=\s)//g

\s+(?=\s) will match all the spaces in the middle of the string and leave one.