Perl正则表达式替换不包括其他模式的模式

时间:2012-08-15 12:00:55

标签: regex perl

我有一个字符串如下。

$line = 'this is my string "hello world"';

我希望有一个正则表达式来删除字符串中除“Hello world”区域之外的所有空格字符。

我使用下面的内容来删除空格字符,但它会删除所有字符。

$line=~s/ +//g;

如何在“Hello world”之间排除区域,我得到如下字符串?

thisismystring"hello world"

由于

5 个答案:

答案 0 :(得分:4)

由于您可能希望正确处理引用的字符串,因此您应该查看Text::Balanced模块。

使用它将文本拆分为引用部分和非引用部分,然后仅对非引用部分进行替换,最后再将字符串连接在一起。

答案 1 :(得分:1)

嗯,这是一种方法:

use warnings;
use strict;

my $l = 'this is my string "hello world some" one two three "some hello word"';
$l =~ s/ +(?=[^"]*(?:"[^"]*"[^"]*)+$)//g;

print $l;
# thisismystring"hello world some"onetwothree"some hello word"

Demo

但我真的不知道是不是应该以其他方式完成(例如通过标记字符串),尤其是如果引号可能不平衡。

答案 2 :(得分:0)

s/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)//g

测试代码here

答案 3 :(得分:0)

Another regex to do it

s/(\s+(".*?")?)/$2/g

答案 4 :(得分:0)

#!/usr/bin/perl
use warnings;
use strict;

sub main {
  my $line = 'this is my string "hello world"';
  while ($line =~ /(\w*|(?:"[^"]*"))\s*/g) { print $1;}
  print "\n";
}

main;