Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Regular Expressions

  • 01-02-2006 07:30PM
    #1
    Closed Accounts Posts: 465 ✭✭


    Evenin' all,

    Any regular expressions experts out there? I've got this:

    ^(([\w]*\d+[a-zA-Z]+)|([a-zA-Z]+\d+[\w]*))\d*$

    which checks a string to see if it contains at least one letter and at least one number, but what I also need is to ensure that the string being searched is between 6 and 12 characters in length {6,12}. I've tried all sorts of combinations of brackets and replacing the *s with {6,12}, and adding:

    \A[\w]{6,12}$

    to the end of the existing line, all to no avail. If there's anyone who can put this out of my misery, I'd really appreciate it. While you're at it, if you can recommend a good book with in-depth explanations of regexps, I'd appreciate that too.

    Thanks for any help you can give!

    G


Comments

  • Registered Users, Registered Users 2 Posts: 1,275 ✭✭✭bpmurray




  • Registered Users, Registered Users 2 Posts: 6,679 ✭✭✭daymobrew


    Maybe a single regular expression can do all that you need but that would be beyond me. For easier maintenance in the future its best to try to keep it simple, even if it ends up being longer.
    I just added a regex to check the length.
    #!/usr/bin/perl -w
    use strict;
    
    my @strs = qw/ a1b2c abcedfg a1q2w3w abcd 1234 12345678901q  abcdefghijklmn1 /;
    
    foreach my $str ( @strs )
    {
      # "[a-zA-Z]" abbreviated to "\w" and redundant [] removed.
      if ( $str =~ /^((\w*\d+\w+)|(\w+\d+\w*))\d*$/ && $str =~ /^.{6,12}$/ )
      {
        print "$str = MATCHES\n";
      }
      else
      {
        print "$str = No match\n";
      }
    }
    
    a1b2c = No match
    abcedfg = No match
    a1q2w3w = MATCHES
    abcd = No match
    1234 = No match
    12345678901q = MATCHES
    abcdefghijklmn1 = No match


  • Closed Accounts Posts: 465 ✭✭Garibaldi


    Cheers, gents. My bacon has been saved. :)


  • Registered Users, Registered Users 2 Posts: 6,679 ✭✭✭daymobrew


    # "[a-zA-Z]" abbreviated to "\w" and redundant [] removed.
    
    I was just reading through a regex book - \w matches digits too, so cannot be used as a substitute for "[a-zA-Z]". So, use your original regex with the length check regex.


Advertisement