Regular expression for 7 digits followed by an optional 3 letters

10,597

Solution 1

You probably need to use anchors at the ends. Further your regex can be simplified to: -

^\d{7}[a-z]{0,3}$
  • \d{7} matches exactly 7 digits. You don't need to use \d 7 times for that.
  • {0,3} creates a range, and matches 0 to 3 repetition of preceding pattern,
  • Caret(^) matches the start of the line
  • Dollar($) matches the end of the line.

Solution 2

^(\d){7}[a-z]{0,3}$ might work well. The ^ and $ will match the start and end of line respectively.

Solution 3

You may want to make sure you are matching the entire string, by using anchors.

^(\d)(\d)(\d)(\d)(\d)(\d)(\d)([a-z])?([a-z])?([a-z])?$

You can also simplify the regex. First, you don't need all those parentheses.

^\d\d\d\d\d\d\d[a-z]?[a-z]?[a-z]?$

Also, you can use limited repetition, to prevent repeating yourself.

^\d{7}[a-z]{0,3}$

Where {7} means 'exactly 7 times', and {0,3} means '0-3 times'.

Share:
10,597
Lil' Bits
Author by

Lil' Bits

Healthcare analytics software engineer M.S. in Computer Science B.S. in Computer Science, minor in mathematics A.S. in Computer Science

Updated on June 09, 2022

Comments

  • Lil' Bits
    Lil' Bits almost 2 years

    I'm new to regular expressions, and I'm trying to validate receipt numbers in our database with a regular expression.

    Our receipts can come in the following formats:

    • 0123456 (Manditory seven digits, no more, no less)
    • 0126456a (Manditory seven digits with one letter a-z)
    • 0126456ab (Manditory seven digits with two letters a-z)
    • 0126456abc (Manditory seven digits with three letters a-z)

    I've tried using a bunch of different regex combinations, but none seem to work. Right now I have:

    (\d)(\d)(\d)(\d)(\d)(\d)(\d)([a-z])?([a-z])?([a-z])?
    

    But this is allowing for more than seven digits, and is allowing more than 3 letters.

    Here is my VBA function within Access 2010 that will validate the expression:

    Function ValidateReceiptNumber(ByVal sReceipt As String) As Boolean
    
        If (Len(sReceipt) = 0) Then
            ValidateReceiptNumber = False
            Exit Function
        End If
    
        Dim oRegularExpression     As RegExp
    
    '   Sets the regular expression object
        Set oRegularExpression = New RegExp
    
        With oRegularExpression
    '   Sets the regular expression pattern
            .Pattern = "(\d)(\d)(\d)(\d)(\d)(\d)(\d)([a-z])?([a-z])?([a-z])?"
    
    '   Ignores case
            .IgnoreCase = True
    
    '       Test Receipt string
            ValidateReceiptNumber = .Test(sReceipt)
    
        End With
    End Function