In Perl, how can I remove all spaces that are not included in double quotes?

I am contacting the suggestion of some regular expression that will remove all space characters from the string if it is not inside double quotes (").

Example line:

some string with quoted text

Result:

somestring with quoted text

So far I have come up with something like this:

    $str =~ /"[^"]+"|/g;

But it does not seem to give the expected result.

I honestly am very new to Perl and have not had too much experience in regex. Therefore, if someone who wants to answer will also be ready to give some idea of ​​why and how cool it would be!

Thank!

EDIT

The string will not contain escape files

In fact, it should always be formatted as follows:

Some.String = "Some value"

Some.String = " "

+3
6

, split . .

use strict;
use warnings;

my @line = split /("[^"]*")/;
for (@line) {
    unless (/^"/) {
        s/[ \t]+//g;
    }
}
print @line;  # line is altered 

, , . , . , .

script :

perl -n script.pl inputfile

.

perl -n -i.bak script.pl inputfile

inputfile, inputfile.bak.

, , .

Some.String = "Some Value"

Some.String="Some Value"
+5

:: ParseWords :

#!/usr/bin/env perl

use strict;
use warnings;
use Text::ParseWords;

my @strings = (
    q{This.string = "Hello World"},
    q{That " string " and "another   shoutout to my   bytes"},
);

for my $s ( @strings ) {
    my @words = quotewords '\s+', 1, $s;
    print join('', @words), "\n";
}

:

This.string="Hello World"
That" string "and"another   shoutout to my   bytes"

Text::ParseWords , - , ; -)

, , - , . , , .

+3

split, join .

, , split, , .

Here is a sample code.

use strict;
use warnings;

my $source = <<END;
Some.String = "Some Value";
Other.String = "Other Value";
Last.String = "Last Value";
END

print join '', map {s/\s+// unless /"/; $_; } split /("[^"]*")/, $source;

Output

Some.String= "Some Value";Other.String = "Other Value";Last.String = "Last Value";
+1
source

I would just skip the char string on char. This way you can also handle escaped strings (just add the isEscaped variable).

my $text='lala "some thing with quotes " lala ... ';
my $quoteOpen = 0;
my $out;

foreach $char(split//,$text) {
  if ($char eq "\"" && $quoteOpen==0) {
    $quoteOpen = 1;
    $out .= $char;
  } elsif ($char eq "\"" && $quoteOpen==1) {
    $quoteOpen = 0;
    $out .= $char;
  } elsif ($char =~ /\s/ && $quoteOpen==1) {
    $out .= $char;
  } elsif ($char !~ /\s/) {
    $out .= $char;
  }
}

print "$out\n";
0
source

Splitting into double quotes, removing spaces only from even fields (i.e. in quotation marks):

sub remove_spaces {
    my $string = shift;
    my @fields = split /"/, $string . ' '; # trailing space needed to keep final " in output
    my $flag = 1;
    return join '"', map { s/ +//g if $flag; $flag = ! $flag; $_} @fields;
}
0
source

This can be done using regex:

s/([^ ]*|\"[^\"]*\") */$1/g

Note that this will not handle any quotation marks inside quotation marks.

0
source

All Articles