Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How to match last character of string, even if it happens to be a newline?

by AnomalousMonk (Chancellor)
on May 12, 2019 at 14:56 UTC ( #1233645=note: print w/replies, xml ) Need Help??


in reply to How to match last character of string, even if it happens to be a newline?

By default, the  . (dot) regex metacharacter matches everything except a newline. Use the  /s modifier to make dot match everything.

c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(pp); ;; for my $s (qq{yz}, qq{yz\n}) { $s =~ m{ (.) \z }xms; printf qq{in %s matched %s \n}, pp($s), pp($1); } " in "yz" matched "z" in "yz\n" matched "\n"
See also  \z for "absolute end of string" anchor.

Update: You're also running into an interaction with  $ which matches | which by default matches at "the end of the line (or before newline at the end)", so even with the  /s modifier, the first position at which  .$ can possibly match (scanning from left to right) is before a newline, if present; remember that the matching rule is leftmost longest.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: How to match last character of string, even if it happens to be a newline?
by Allasso (Monk) on May 12, 2019 at 15:11 UTC
    Yes, the \z anchor does, the trick, thanks!
Re^2: How to match last character of string, even if it happens to be a newline?
by Allasso (Monk) on May 12, 2019 at 15:17 UTC
    Using \z, I don't seem to need multiline, simply m@(.)\z@s
      Using \z, I don't seem to need multiline ...

      That's because  \z is always the absolute end-of-string anchor; no modifiers apply. I always use  \A \z \Z because they have invariant behavior. For the same reason, I nail down the  ^ $ operators by always using the  /m modifier. (I then use the  ^ $ operators only with newlines embedded within a string.)


      Give a man a fish:  <%-{-{-{-<

Re^2: How to match last character of string, even if it happens to be a newline?
by Allasso (Monk) on May 12, 2019 at 15:04 UTC
    er... I _did_ use s modifier :-/

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2019-06-20 19:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (91 votes). Check out past polls.

    Notices?