finding the first match in a string

S

size14feet

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
 
T

Tad McClellan

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}/;
}
 
N

nobull

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top