use strict;
use warnings;
my $str = q{"joe smith" NOT jane "abhi and makie"};
print $str, "\n";
while ( $str =~ /"[^"]+"/g ) {
substr($str, $-[0], $+[0] - $-[0]) =~ s/\s+/~~/g;
}
print $str, "\n";
output
"joe smith" NOT jane "abhi and makie"
"joe~~smith" NOT jane "abhi~~and~~makie"
0
假设您没有转义引号并且它们都已配对:
$s='"joe smith" NOT jane "abhi and makie"';
$s =~ s/ (?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)/~~/g;
print $s, "\n";
use strict;
use warnings;
while ( <DATA> ) {
s!("[^"]*")! my $aa = $1; $aa =~ s/ /~~/g; $aa !eg;
print;
}
__DATA__
"joe smith" NOT jane "abhi and makie"
3 回答
我知道做这种事情的最简单方法是使用
m/.../g
迭代目标字符串的所有相关子字符串 . 然后使用@-
和@+
内置数组以及substr
作为左值来修改这些子串 .此代码演示
output
假设您没有转义引号并且它们都已配对:
s///
后缀为s///
命令允许在替换文本中使用代码 . 在下面的代码中,s!!!
在双引号中找到名称,然后传递为$1
. 替换部件中的代码将$1
保存为$aa
,因为$1
是只读的,因此无法修改 . 内部s///
用波浪号替换空格 . 最终$aa
返回替换文本 . 最终g
使s!!!
对该行上的每个双引号文本起作用 .请注意,此代码假定双引号在输入文本中正确 balancer .