Friday, July 4, 2008

Perl: Regular expression to squeeze spaces

Share at Facebook

While coding, you may requires to squeeze the spaces from a given string sometimes. I'm going to give an easy regular expression that will remove all the spaces from the provided string. I'm providing the example using Perl script which is my favorite. But you can use the regex into your PHP/Python/Ruby scripting language.

## Given string, needs to squeze
my $string = "squeezing spaces fro m t h e string";
## regex that squeeze the spaces
$string =~ s/\s//g;
print "$string \n";

Here \s means the space. Wherever any space found from the string it will be replaces with empty('').

If you think you need to remove other character, not the space. Then you can squeeze the string with that character too. For example you need to squeeze all the a's from the string. Just replace the \s with a, and it will replace all a's into empty(''). Example code.
$string =~ s/a//g;

If you need to squeeze with multiple characters. You can use all chars inside [] and it will remove any character that will found inside []. For example you need to squeeze for space, a, b and c. Then inside then it will be [\sabc]. \s for space.
$string =~ s/[\sabc]//g;

You can separate the characters with pipe(|) too instead of inside []. For example
$string =~ s/\s|a|b|c//g;

Thats all for today. Hope you enjoyed the article. For more you can take a look at my blog


Anonymous said...

Cool, exactly what I needed!
I'm changing some existing code and couldn't make sense of

Tony Hansmann said...

# to replace n spaces or tab with a single instance, leaves newlines alone:
echo -e "\t\t\ttab space \n\n\n\n newline"
echo -e "\t\t\ttab space \n\n\n\n newline" | perl -pe 's{(\s)+}{$1}xmgs;'