http://qs321.pair.com?node_id=11128786


in reply to Re^2: You won't believe what this regular expression does!
in thread You won't believe what this regular expression does!

Thanks! :)

But please note the second fOO

DB<55> p "hello\nfoo" =~ s/o*(?:\n|\z)/O/gmr; hellOfOO DB<56>

I'm busy right now, but I seem to remember that one could use features for atomic matches...

I'll try later...°

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

update

°) nah doesn't help, since it's not a backtracking problem.

Replies are listed 'Best First'.
Re^4: You won't believe what this regular expression does!
by haukex (Archbishop) on Feb 26, 2021 at 08:26 UTC
    But please note the second fOO

    Yes, good point! I think the main question is what the intent of the regex is. If it's "replace any o's at the end of each line", then the better solution is, as you said, /o+$/, and using o* is the "mistake".

      No, the intent is to ensure that the string ends in just one o, no less, no more than one.

      In real life, those lines were paths, and I wanted all of then ending in a single slash. For instance:

      /foo --> /foo/ /foo/ --> /foo/ /foo////// --> /foo/
        In real life, those lines were paths, and I wanted all of then ending in a single slash.

        Ah, I see. You want canonpath from File::Spec ;-) (doesn't add the trailing slash, but there are multiple possible solutions for that as well)

        And this is admittedly not the prettiest solution, but it works: s{(?| /* (\n) | /+ (\z) | [^/] \K (\z) )}{/$1}mgrx. Or just split the input string on \n...