in reply to searching for a substring in a string

$i =~ s/.*(test.*?\.txt).*/test29-01-05\.txt/
Note the question-mark.

Being right, does not endow the right to be rude; politeness costs nothing.
Being unknowing, is not the same as being stupid.
Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Replies are listed 'Best First'.
Re^2: searching for a substring in a string
by Ardemus (Beadle) on Feb 02, 2005 at 18:58 UTC
    To expand upon the solution:
    $string = "Cats and dogs shouldn't eat hot dogs"; $string =~ m/.*dogs/; # Greedy Quantifier $string =~ m/.*?dogs/; # Lazy Quantifier
    Greedy quantifiers gobble up every character they can, then back off until a match is made. Lazy quantifiers find as little as possible, then expands what it matches until it can match the rest of the regex. The first search matches the entire string, while the second search matches, "Cats and dogs".

    If you're getting into Regex, I'd recommend 'Mastering Regular Expressions'. It will provide some invaluable insights into these sorts of things.

    Ardemus "This, right now, is our lives."
Re^2: searching for a substring in a string
by Anonymous Monk on Feb 02, 2005 at 17:43 UTC
    Thank you

    If I want to update the line in the same file, how do I do it without just appending to the last line.

    Is there a way I can just update a single line wherever it exists in the file to the same location?

    Thanks

      Clunky, but clear, change that line in the array and re-write the file:
      open ( FH, "p.txt" ); my @output = <FH>; close ( FH ); open ( FH, ">p.txt" ); for $i (0 ..#@output) { if ($output[$i] =~ /.*(test.*\.txt).*/) { $output[$i] =~ s/.*(test.*\.txt).*/test29-01-05\.txt/ last; } for $i (0 ..#@output) { print "$output[$i]"; } close ( FH );

      Forget that fear of gravity,
      Get a little savagery in your life.

        Thank you all for the reply.

        Is there a way to check also after how many semi-colons the particular string is located in a string?

        So, if

        myFiles = test1234.txt; hello3456.txt; world7890.txt;

        Then, test1234.txt is located after Zero semicolons

        and hello3456.txt is located after One semicolons

        and world7890.txt is located after Two semicolons

      I don't know if I'm reading you right but: perl -p -i.bkup -e "s/.*(test.*?\.txt).*/test29-01-05\.txt/;" p.txt, might do what you want. (see perlrun)

      "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce