finding the first match in a string

Discussion in 'Perl Misc' started by size14feet@gmail.com, Apr 9, 2005.

  1. Guest

    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
     
    , Apr 9, 2005
    #1
    1. Advertising

  2. <> 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
    Perl programming
    Fort Worth, Texas
     
    Tad McClellan, Apr 9, 2005
    #2
    1. Advertising

  3. Guest

    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.
     
    , Apr 9, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. hiwa
    Replies:
    0
    Views:
    639
  2. Victor
    Replies:
    2
    Views:
    649
    Victor
    May 17, 2004
  3. Angus
    Replies:
    16
    Views:
    590
    Tim Rentsch
    Nov 18, 2010
  4. Old Echo
    Replies:
    1
    Views:
    182
    Adam Shelly
    Sep 4, 2008
  5. Replies:
    2
    Views:
    80
Loading...

Share This Page