paribasu has asked for the wisdom of the Perl Monks concerning the following question:

I have this following lines of code.
$line="src/utility/include/abc.pl@@/main/f1/f2/1 /main/f1/f3/f6/f7/3, /mian/1; 123\"\;"; print "TEST : .$line\n"; $line =~ s/\/main\/.*?(,|;|\"|\s)/%I%/g; print "\nReplacing with %I% : $line\n";
Output : Replacing with %I% : /src/utility/include/abc.pl@@%I% %I% %I% 123";

Now I don't want the delimeter to be replaced in the above cases but I have to take delimeter inside my search string for replacement of the /main/.*? portion i.e I want perl to repalce upto the first occurence of any of the delimeters (,|;|\"|\s) whenever my search condition satisfy but not the delimeter itself. Thanks & Regards

Replies are listed 'Best First'.
Re: search and repalce excluding delimeter
by grizzley (Chaplain) on May 09, 2008 at 06:39 UTC
    Use assertion:
    $line =~ s/\/main\/.*?(?=,|;|"|\s)/%I%/g;

      The following is cleaner.

      $line =~ s{/main/[^,;"\s]*}{%I%}g;

      It's a little different, but it'll behave the same if /main/ is always followed by one of the delimiters.

      Thanks grizzley.

      That did the job.

Re: search and repalce excluding delimeter
by Corion (Patriarch) on May 09, 2008 at 06:41 UTC

    If I understand you correctly, you want as result:

    src/utility/include/abc.pl@@/main/f1/f2/1 %I%, %I%;123";";

    right?

    You can either use the matched delimiter and add that into the replacement as well:

    $line =~ s!/main/.*?([,;"\s])!%I%$1!g;

    (I've changed the regex delimiter to ! so I don't need to escape the slashes and put the alternation into a character class)

    Or you can use a lookahead assertion:

    $line =~ s!/main/.*?(?=[,;"\s]!%I%!g;