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

Re: grep regex exact match last n positions

by nvivek (Vicar)
on Apr 13, 2010 at 05:36 UTC ( #834405=note: print w/replies, xml ) Need Help??

in reply to grep regex exact match last n positions

If you want to match the string in the array end with same number of characters as the pattern.Then,you try this.
my $search = "foo"; my $len=length($search); #finding the length of the pattern my @array = ("s1 bar", "foo", "s3 foo"); print grep {/.*\b(.{$len})/;$_=$& if $1 eq $search;} @array; #checking whether the end characters of the string in the array is same as the pattern given

Replies are listed 'Best First'.
Re^2: grep regex exact match last n positions
by JavaFan (Canon) on Apr 13, 2010 at 07:02 UTC
    That's an expensive way of doing substr! Not to mention that your regexp actually doesn't find the last 3 characters - it finds the first 3 characters following the last word boundary.
    print grep {substr($_, -length($search)) eq $search} @array;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://834405]
[shmem]: Discipulus: the <<>> operator is quite new, it is in perl5.24 for instance
[Discipulus]: ah! thanks shmem it works in strawberry 5.24
[shmem]: ah. Introduced in 5.22.0, see perl5220delta
[Discipulus]: if so the previous error is a bit misleading, anyway
[shmem]: well, previous to that << was always treated as the left-shift operator

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2017-07-21 09:03 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (320 votes). Check out past polls.