SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2005
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Regular Expressions Help

    I am trying to create a regular expression to help me validate a particular string that users will be passing into my application. I thought I had it figured out until I found a few test cases that my expression gave a false positive for. Here are the details:

    1. The first six characters will be letters or spaces.
    2. The first character must be a letter.
    3. If the first six characters are not all letters, then the rest of the six are padded with spaces.

    Here are some examples of valid strings:

    Good:
    Code:
    ABCDEF0123
    GHIJK 0123
    LMNO  0123
    PQR   0123
    ST    0123
    U     0123
    So I quickly whipped up the below expression to validate these strings:

    Code:
    ([a-zA-Z]){1}([a-zA-Z]|\s){5}\d{4}
    The problem is this can create false positives because I am not properly meeting requirement number 3. Here are some strings that cause false positives:

    Bad:
    Code:
    ABCD F0123
    GHI JL0123
    MN PQR0123
    S UVWX0123
    I'm not the best at regular expressions so I am kind of stumped as to how to proceed. How do I check the first six characters so that they are letters until a space is found and then it is padded until it reaches 6 characters. Thank you in advance for your help.
    Last edited by viper2843; Feb 22, 2010 at 22:13. Reason: messed up the regex.

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    I can't think of a way to directly check for letters with trailing spaces to pad out to the specific length without checking each combination separately such as

    Code:
    ^([a-zA-Z]     )|([a-zA-Z]{2}    )|([a-zA-Z]{3}   )|(a-zA-Z){4}  )|([a-zA-Z){5} )|([a-zA-Z]{6})\d{4}$
    Alternatively testing two expressions separately would be shorter.

    Code:
    ^[a-zA-Z]{1,6} {0,5}\d{4}$
    ^[a-zA-Z ]{6}\d{4}$
    the first checks the spaces are after the letters while the second checks the total length.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2005
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for your reply, felgall. The example you gave was perfect. I was able to finish my validation code today. Thank you very much for your help!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •