开发者

perl pattern matching one by one and process it

开发者 https://www.devze.com 2023-04-10 13:32 出处:网络
I have a string [something]text1[/something] blah blah [something]text2[/something] I need to write a Perl script to read what is in the [something] tag, process it to \"text-x\", and put it back

I have a string

[something]text1[/something] blah blah [something]text2[/something]

I need to write a Perl script to read what is in the [something] tag, process it to "text-x", and put it back with an [otherthing] tag. So the above string should be

[otherthing]text-1[/otherthing] blah blah [otherthing]text-2[/otherthing]

Processing "textx" to "text-x" is not one step process.

So this is solution that I have till now:

m/[something](?<text>.*)[/something]/

This will get m开发者_如何学Ce the string in between and I can process that to "text-x" but how do I put it back in the same place with [otherthing]text-x[/otherthing]?

  1. How do I use s/// in this case?
  2. How to do it for the whole string one by one ?


You can use the /e switch on s/// to evaluate the right hand side before using the result as the substitution, and the /g flag to do this for every match.

Here is a simple example:

use 5.12.0;

my $str = ">1<  >2<  >34<";

$str =~ s/>(\d+)</">>".process("$1")."<<"/eg;

say $str;

sub process {
    return "x" x $_[0];
}


This should come close. It uses the /e modifier to allow you to do processing in the replacement side of the regex and so it calls the fix_textx function where you can do multiple steps.

The normal way of iterating over matches is with the /g modifier.

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

my $string = '[something]text1[/something] blah blah [something]text2[/something]';

$string =~ s{\[something\](text[^[]*)\[\/something\]}
            {'[otherthing]' . fix_textx($1) . '[/otherthing]'}ge;

print $string;

sub fix_textx {
    my ($testx) = @_;
    $testx =~ s/text\K(.*)/-$1/;
    return $testx;
}

EDIT: fixed the square bracket. Thanks @tadmc


In this particular case, you can accomplish what you're trying to do by splitting the string on "[something]" and then processing the beginning of each piece (except the first one), then joining the pieces back together when you're done.

I don't know if there is a general way to iterate over the regex matches in a string in Perl. I'm hoping someone else will answer this question and educate me on that.

0

精彩评论

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

关注公众号