简体   繁体   English

如何在perl中单独替换顺序空格

[英]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". 我想用“\\”替换“a b”中的每个空格,预期的输出是“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". 输出是“a \\ b”但不是“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 我们的想法是匹配\\ s,它会一遍又一遍地执行它,直到匹配任何\\ s类型字符,空白字符集正则表达式

First up, as a previous answerer has already mentioned, you're just missing the /g ("global") modifier on your substitution regular expression. 首先,正如之前的回答者已经提到的那样,你只是在替换正则表达式上缺少/ g(“全局”)修饰符。

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. 在这种情况下,您可能希望使用quotemeta()内置。

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

For more information see perldoc quotemeta . 有关更多信息,请参阅perldoc quotemeta

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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