开发者

Apply regexp replace only to quoted piece

开发者 https://www.devze.com 2023-03-13 16:08 出处:网络
I need to apply a regexp filtration to affect only pieces of text within quotes and I\'m baffled. $in = \'abc \"d ef\" gh \"ij\" k l\';

I need to apply a regexp filtration to affect only pieces of text within quotes and I'm baffled.

 $in = 'ab  c "d e  f" g   h "i    j" k l';
 #...?
 $inquotes =~ s/\s+/_/g; #arbitrary regexp working only on the pieces inside quote marks
 #...?
 $out = 'ab  c "d_e_f" g   h "i_j" k l';

(the final effect can strip/remove the quotes if that makes i开发者_如何学JAVAt easier, 'ab c d_e_f g...)


You could figure out some cute trick that looks like line noise.

Or you could keep it simple and readable, and just use split and join. Using the quote mark as a field separator, operate on every other field:

my @pieces = split /\"/, $in, -1;

foreach my $i (0 ... $#pieces) {
    next unless $i % 2;
    $pieces[$i] =~ s/\s+/_/g;
}

my $out = join '"', @pieces;


If you want you use just a regex, the following should work:

my $in = q(ab  c "d e  f" g   h "i    j" k l);

$in =~ s{"(.+?)"}{$1 =~ s/\s+/_/gr}eg;
print "$in\n";

(You said the "s may be dropped :) )

HTH,
Paul


Something like

s/\"([\a\w]*)\"/

should match the quoted chunks. My perl regex syntax is a little rusty, but shouldn't just placing quote literals around what you're capturing do the job? You've then got your quoted string d e f inside the first capture group, so you can do whatever you want to it... What kind of 'arbitrary operation' are you trying to do to the quoted strings?

Hmm.

You might be better off matching the quoted strings, then passing them to another regex, rather than doing it all in one.

0

精彩评论

暂无评论...
验证码 换一张
取 消