Help with regular expression please?

Discussion in 'Perl Misc' started by Billy N. Patton, Oct 10, 2007.

  1. Here is the simplified code I have attempted. It failed me by finding 31ZB1 to be the same as 31ZB11

    __BEGIN__

    $focusRule = '31ZB1';
    # match v v v v
    @l = ( qw ( 31ZA1 31ZB1 31ZB11 31ZB15 175A2 31ZU7 31ZB 31ZB1a 31ZB1b ));
    # n = number

    # a = alpha char

    # + is one or more

    # ? one or more may or may not be there

    # the rule names are built

    # n+a+n?a?n?

    # so the possible correect permutations are

    # n+a+

    # n+a+n+

    # n+a+n+a+

    # n+a+n+a+n+

    # 31ZB1 31ZB 31ZB1a 31ZB1b1 all these should match $focusRule

    # 31ZB1 and 31ZB11 are different

    # I also need to set $focusRule to '31ZB' and have it find the same set.

    $found = 0;
    foreach $rule (@l ) {
    my $a1 = ($rule =~ /^$focusRule[abc123]?$|,$focusRule[abc123]/) ? 1 : 0;
    my $a2 = ($focusRule =~ /^$rule[abc123]?/) ? 1 : 0;
    print "focusRule = '$focusRule' , rule = '$rule', a1 = $a1 , a2 = $a2\n";
    if ($a1 || $a2) {
    print "focusRule = '$focusRule' matches '$rule'\n";
    $found++;
    }
    }
    print "found = $found\nshould have found 4";


    __END__
     
    Billy N. Patton, Oct 10, 2007
    #1
    1. Advertisements

  2. You appear to be saying you are inventing your own simple regex
    grammar

    So the translation from your grammar to Perl's

    my %translate_pattern_token = (
    'n' => '\d'
    'a' => '[[:alpha:]]'
    '+' => '+'
    '?' => '*'
    );

    So if a $rule is a pattern in your notation you could convert it to a
    Perl regex thus...

    my $regex = join '', map { $translate_pattern_token{$_} } split //,
    $rule;

    # E&OE
    OK now you've lost me. What did you mean by that?
     
    Brian McCauley, Oct 11, 2007
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.