简体   繁体   中英

Perl regex issue with multiple line matching

My goal is to extract a part of a big string on multiple lines (this string is A). The substring extracted (call it B) will have a new string added to it, the new substring is C. Finally in A, I will replace B by C.

Here is my code with some explanations...my substring B looks like this :

$B = 'define category "Allowed"\n\twww.toto.com\n\twww.tata.com\n\t{...}\nend category "Allowed

It's a list of websites. (in real, the string is bigger - hundreds of websites inside) It starts with define category "Allowed" and finishes with end category "Allowed" . Websites are separated by "\\n\\t".

I want all URLs so I do this

if ( $A =~ m/define category "Allowed"\n\t(.*)\nend category "Allowed"/s) {
    my $list = $1 ;

Then I put my list in an ARRAY

    my @items = split /\n\t/, $list ;

Then I add my new website "www.titi.com"

   push @items, "www.titi.com" ;

Then I create a new list

    my $new_list = join "\n\t", @items;

And finally, I replace the old list by the new one

   $A =~ s/$list/$new_list/;
}

The issue is that $A is not modified (new website is not added).

For information, I work with arrays because this function add a new website, but I will need to be able to remove websites from the list too, so it's easier (for me) to work with arrays instead of working on the string directly.

I made some investigations, and I found that when I extract "$list" and then verify it matches with $A, the result is negative :

if ( $A =~ m/$list/s ) { print "MATCH\n" ; }

...it never prints "MATCH"...What am I missing ?

Since $list is extracted from a pattern matching, it must match with the original string, no ?

I found an alternative but it's dirty : I only replace the last website by last website AND new website like this :

$A =~ s/$items[$#items-1]/$items[$#items-1]\n\t$items[$#items]/;

This works but it doesn't satisfy me.

The issue is that $A is not modified...

I tried the code and it modified $A correctly. I tried with the following $A and $B :

my $B = 'define category "Allowed"' 
    . "\n\twww.toto.com\n\twww.tata.com\n\t{...}\nend category "
    . '"Allowed"';
my $A = 'xxxxxxxxxxxxx' . $B . 'yyyyyyyyyyyyyyyyyyyyyyyyy'; 

Please show more of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM