Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: regex for string

by markkawika (Monk)
on Aug 18, 2009 at 18:09 UTC ( [id://789544]=note: print w/replies, xml ) Need Help??


in reply to regex for string

It's tough to do this for edge cases in one regex, so I would solve it in two. First, grab the first character:

$str =~ m/\A(.)/xms; my $first_character = $1;

Then, grab the last character:

$str =~ m/(.)\z/xms; my $last_character = $1;

If you could guarantee the string was at least two characters long, you could do it in one regex:

$str =~ m/\A(.).*(.)\z/xms; my $first_character = $1; my $last_character = $2;

If you insist on handling all edge cases in one regex, here's one way:

$str =~ m/\A(.).*?(.?)\z/xms; my $first_character = $1; my $last_character = $2; $last_character = $first_character if ! $last_character;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-09-10 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.