Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   finding the first match in a string (http://www.velocityreviews.com/forums/t891712-finding-the-first-match-in-a-string.html)

size14feet@gmail.com 04-09-2005 12:18 AM

finding the first match in a string
 
must simple way to do this...

I have a string. I have several patterns to match for. I'd like
to determine which pattern finds a match in the string first & at what
position.

Anyone have an elegant way to do this? I don't mind using a CPAN
module, if need be.


much appreciated-
matt


Tad McClellan 04-09-2005 02:45 AM

Re: finding the first match in a string
 
size14feet@gmail.com <size14feet@gmail.com> wrote:

> I have a string. I have several patterns to match for. I'd like
> to determine which pattern finds a match in the string first & at what
> position.
>
> Anyone have an elegant way to do this?



--------------------------------
#!/usr/bin/perl
use warnings;
use strict;

my $string = 'foo TX bar 12345 baz 98765-1234';

my %patterns = (
street => qr/\d+\s+.*/,
zip => qr/\d{5}(-\d{4})?/,
state => qr/\b[A-Z][A-Z]\b/,
);

print "$string\n";
print "01234567890123456789\n";

foreach my $type ( keys %patterns ) {
print "$type at ", length($1), "\n" if $string =~ /(.*?)$patterns{$type}/;
}
--------------------------------

Making note of the lowest value of length($1) is left as
an exercise for the reader.


--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas

nobull@mail.com 04-09-2005 07:49 AM

Re: finding the first match in a string
 
size14feet@gmail.com wrote:

> I have a string. I have several patterns to match for. I'd like
> to determine which pattern finds a match in the string first &
> at what position.


You want the special variable @-

You have to make sure the patterns themselves contain no capturing
(...) but they can, of course, contain grouping parentheses (?:...).

if ( /(pat1)|(pat2)|(pat3)/ ) {
print "Pattern $#- matched at position $-[0]\n";
}

Note because of the way the regex engine works this may be
significantly less efficient than checking each pattern separately in a
loop if you have a large number of patterns.



All times are GMT. The time now is 05:23 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.