Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^3: My regex works, but I want to make sure it's not blind luck

by haukex (Archbishop)
on Dec 22, 2020 at 08:08 UTC ( [id://11125604]=note: print w/replies, xml ) Need Help??


in reply to Re^2: My regex works, but I want to make sure it's not blind luck
in thread My regex works, but I want to make sure it's not blind luck

Is there a way to tell regex to work from right to left?

No. One of the basic principles of the regex engine is that it works from left to right (GrandFather's suggestion of reverseing the string is a workaround/hack, though I personally have never seen anyone actually do this in production). Another basic principle is that the engine will stop at the first successful match, which sometimes leads to confusion when, for example, people expect .* to match more than "" (though in your example in the root node you're using the ^ $ anchors to help with that). Combine this with the idea of backtracking (Update: which of course does work from right to left, but too much backtracking can be very inefficient) and hopefully this will lead to a better understanding :-) I very much recommend a read of perlretut, and if you want to see your regex in action, then install Regexp::Debugger and run e.g. perl -MRegexp::Debugger -e '"foo.bar" =~ /^.*(\..*)$/'

Replies are listed 'Best First'.
Re^4: My regex works, but I want to make sure it's not blind luck
by Marshall (Canon) on Dec 23, 2020 at 19:16 UTC
    I had a hard time thinking of an example where reversing the string before using a regex made sense. I came across this little gem..
    use strict; use warnings; sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; } foreach (qw(-1000 23000000)) { print "$_ transformed to: ",commify($_),"\n"; } __END__ -1000 transformed to: -1,000 23000000 transformed to: 23,000,000
    There are of course ways to do this with printf().

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125604]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2024-04-25 22:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found