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

Hello monks,

I am a novice to perl and am facing problem in acheiving replacement in the middle of a string. I am posting this request to you as this task must be acheived in aquick time.

Here is the String $str ="//111.11.112.12/abc/main/myfolder/docs";

i need to find the pisotion of the "main" and replace all the text occuring upto the "/" preceding the "abc".

Iattempted with search and replace but the problem is, ineed to search for the "/main" and replace anything before it till the previous "/" (the slash before the "abc" in this case).

I shall be greatly obliged.

with regards

A

Replies are listed 'Best First'.
Re: Regex for replacement
by davido (Cardinal) on Jul 08, 2004 at 06:28 UTC
    s!^.*(/[^/]+/main)!$newtext$1!

    Note, I used '!' as the quoting delimiter to avoid the need for escaped slashes.


    Dave

Re: Regex for replacement
by davidj (Priest) on Jul 08, 2004 at 06:33 UTC
    my $str = "//111.11.112.12/abc/main/myfolder/docs"; my $replace = "something"; $str =~ s#.+(?=/main)#$replace#"; print "str now = $str";
    output:
    str now = something/main/myfolder/docs

    davidj

    update:Thanks davido for pointing out the error in my response. I guess I need to read the questions a little more closely. Your solution (in addition to being correct :) ) is much better.
    davidj
Re: Regex for replacement
by ercparker (Hermit) on Jul 08, 2004 at 06:46 UTC
    my $str = "//111.11.112.12/abc/main/myfolder/docs"; $str =~ s[^.+?(/\w+?/main.*)$][whatever$1];
Re: Regex for replacement
by murugu (Curate) on Jul 08, 2004 at 06:49 UTC

    Misread the question earlier.

    English is not my mother language

    s{.+(?=/main)}{what ever u need}g;
      s{.+(?=/main)}{what ever u need}g;

      This solution still doesn't preserve the /abc/, as the OP stated was a requirement. I don't see the need for the /g modifier either.


      Dave