in reply to Matching across newlines without stripping them out

When I first read your question I misinterpreted it. When I then later was about to post my answer I realized that your boldened sentence should be interpreted as "don't fiddle with anything but the match", whereas I first interpreted it as "don't fiddle with the newlines, at all". So my solution keeps the newlines and scatters out your 'jjjjjjj' to the same positions as "uekasdh" were found.

sub replace_keep_whitespace { my ($str, $word, $rep) = @_; $str =~ join('\\n*', split //, $word); my $match = \substr($str, $-[0], $+[0] - $-[0]); my $c = 0; $$match =~ s/[^\n]/substr($rep, $c++, 1)/eg; return $str; } my $str = <<'_DATA_'; s kkjn find ue k asd helkjadfoijejdklk _DATA_ my $word = 'uekasdh'; my $rep = 'j' x length $word; print replace_keep_whitespace($str, $word, $rep); __END__ s kkjn find jj j jjj jekjadfoijejdklk

If the replacement word is longer than the matched word then it's simply ignored at the end. If it's shorter then, well, the remaining chars are removed (but the newlines are kept).

I realize this wasn't what was asked for, but I find the solution pretty enough to post it anyway. ;-)

ihb

Replies are listed 'Best First'.
Re: Re: Matching across newlines without stripping them out
by aquarium (Curate) on Jun 16, 2003 at 10:59 UTC
    vroom: you're assuming /n between each char, when that was just an example.
    original poster: there is no way to do the search without stripping, i.e. no extended perl regex to ignore a certain char. and even with stripping it's not that simple to put the \n's back in the right place, but can be done. certainly not in a single regex. perhaps it might be achievable with the extended code regex, unfortunately i don't have the time right now to play with it to that depth. perhaps you were on the right track to start with...and modularize it enough so the code generates strings for you instead of hardcoding.