Regular expression for 7 digits followed by optional 3 letters

I am new to regular expressions and I am trying to check the check 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 (Mandatory seven digits with one letter az)
  • 0126456ab (Manditory seven digits with two letters az)
  • 0126456abc (Manditory seven digits with three letters az)

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

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

      

But this allows for more than seven numbers and allows for more than three letters.

Here is my VBA function in Access 2010 that will validate an 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

      

+3


source to share


3 answers


You probably need to use end bindings. Further, your regex can be simplified: -

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

      



  • \d{7}

    matches exactly 7 digits

    . You don't need to use \d

    7 times for this.
  • {0,3}

    creates a range and matches 0 to 3 repetitions of the previous pattern,
  • Caret(^)

    matches the beginning of the line
  • Dollar($)

    matches the end of the line.
+10


source


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

can work well. ^

and $

will match the beginning and end of the line, respectively.



+6


source


You may want to make sure you match the entire string 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]?$

      

Alternatively, you can use limited repetition to avoid repeating yourself.

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

      

Where it {7}

means "exactly 7 times", and {0,3}

means "0-3 times".

+3


source







All Articles