首页 文章

用字符串中的双引号替换空格perl regex [关闭]

提问于
浏览
1

我想在perl正则表达式中替换字符串中双引号内的空格 . 喜欢如果有一个字符串:

"joe smith" NOT jane "abhi and makie"

和exxcted输出应该像:

"joe~~smith" NOT jane "abhi~~and~~makie"

任何帮助都会很感激 .

3 回答

  • 0

    我知道做这种事情的最简单方法是使用 m/.../g 迭代目标字符串的所有相关子字符串 . 然后使用 @-@+ 内置数组以及 substr 作为左值来修改这些子串 .

    此代码演示

    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";
    
  • 1

    s/// 后缀为 s/// 命令允许在替换文本中使用代码 . 在下面的代码中, s!!! 在双引号中找到名称,然后传递为 $1 . 替换部件中的代码将 $1 保存为 $aa ,因为 $1 是只读的,因此无法修改 . 内部 s/// 用波浪号替换空格 . 最终 $aa 返回替换文本 . 最终 g 使 s!!! 对该行上的每个双引号文本起作用 .

    use strict;
    use warnings;
    
    while ( <DATA> ) {
        s!("[^"]*")! my $aa = $1; $aa =~ s/ /~~/g; $aa !eg;
        print;
    }
    
    __DATA__
    "joe smith" NOT jane "abhi and makie"
    

    请注意,此代码假定双引号在输入文本中正确 balancer .

相关问题