jkshah jkshah - 1 year ago 61
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+/ /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 Source

You can use something like:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download