简体   繁体   中英

How to substitute sequential spaces individually in perl

I want to replace every space in "a b" with "\\ " and the expected output is "a\\ \\ \\ b".
I have tried the following code but the output did not satisfy.

#!usr/bin/perl -w
use CGI;
my $q = CGI -> new;
print $q -> header();
$input = "a   b";
(my $output = $input) =~ s/\ /\\ /;

the output is "a\\ b" but not "a\\ \\ \\ b".
How can I get it right?

Hmmm

$input = "a   b";

$input =~ s/\s/\\/g;

Tested and works, my test code

#!/usr/bin/perl

$abc = "a          b";

 $abc =~ s/\s/\\/g;

print $abc, "\n";

Cerberus:~ alexmac$ ./testaaa.pl
a\\\\\\\\\\b

This should work nicely for you. The idea is we are matching the \\s and it will do it over and over until your matching any \\s type character, the white space character set regular expressions

First up, as a previous answerer has already mentioned, you're just missing the /g ("global") modifier on your substitution regular expression.

alex@yuzu:~$ perl -E '$str = "a   b"; $str =~ s/ /\\ /g; say $str;'
a\ \ \ b

However going one step further, I wonder if you are looking to escape characters other than spaces. In that case you might want to look into using the quotemeta() builtin.

alex@yuzu:~$ perl -E '$str = q{a   b   ()+?$@%}; say quotemeta $str;'
a\ \ \ b\ \ \ \(\)\+\?\$\@\%

For more information see perldoc quotemeta .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM