regex - Substitution with \s does not work as expected -
i write regex remove more 1 space in string. code simple:
my $string = 'a string has more 1 space'; $string = s/\s+/\s/g;
but, result bad: 'asstringshassmoresthans1sspace'. replaces every single space 's' character.
there's work around instead of using \s substitution, use ' '. regex becomes:
$string = s/\s+/ /g;
why doesn't regex \s work?
\s
metacharacter in regular expression (and matches more space, example tabs, linebreak , form feed characters), not in replacement string. use simple space (as did) if want replace whitespace single space:
$string = s/\s+/ /g;
if want affect actual space characters, use
$string = s/ {2,}/ /g;
(no need replace single spaces themselves).
Comments
Post a Comment