Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Pattern Match/Trim Variables.

by dvergin (Monsignor)
on Feb 17, 2003 at 20:01 UTC ( [id://236091]=note: print w/replies, xml ) Need Help??


in reply to Pattern Match/Trim Variables.

I like to keep my regexes simple.

Strip a dot and some digits from the end of a string:

my $str = '02/17/2003 11:44:19.123'; $str =~ s/\.\d+$//; print "$str\n";
You say you are struggling with regexes, so here is the explanation:

We could *try* to say s/.\d+$// but it happens that the dot is magic (matches most anything). So to match a dot we have to "escape" it with the backslash. Like this: \.

Next comes \d which means "any digit". The plus after it means "one or more". Like this: \d+

Then we have the $   When $ is used at the end of a regex, it means "anchor this match to the end of the string" (there are some nuances here we won't bother with). Actually, in this case we don't need the $ anchor -- we know that there is only one place in the string that will match "a dot followed by some digits". But it is perhaps a kindness to the next human who looks at the code to provide this visual clue that the match is expected to occur at the end of the string. So now we have: \.\d+$

We put this regex snippet into a substitution regex: s/ / / But we leave the second half empty. This means "whatever you matched in the first half of the s///, replace it with nothing at all".

So reading s/\.\d+$// straight off the page, we could translate it as: match a literal dot followed by some digits anchored to the end of the string and replace them with nothing.

Hope that helps.

------------------------------------------------------------
"Perl is a mess and that's good because the
problem space is also a mess.
" - Larry Wall

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-25 11:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found