iDev
iDev

Reputation: 2431

Perl:Regex substitution

I want to write a regex to substitute remove white spaces within my string as follows:

String : user1: group user2 :group2 user3 : group3 to

user1:group user2:group2 user3:group3

What I tried so far is:

$argument =~ s/\s+\:/\:/g;

Upvotes: 2

Views: 182

Answers (2)

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Edit (didn't notice that there could be spaces before the colon, too):

$yourString =~ s/\s*:\s*/:/g;

I think. Note that I do not in any way speak perl.

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208475

You are nearly there:

$argument =~ s/\s*:\s*/:/g;

There is no need to escape the :, and you want to search for whitespace both before and after the colon. Instead of \s+ which searches for one or more, I used \s* which searches for zero or more. That way you will match if there are no spaces before but some after, or vice-versa.

Upvotes: 5

Related Questions