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
source to share
You probably need to use end bindings. Further, your regex can be simplified: -
^\d{7}[a-z]{0,3}$
-
\d{7}
matches exactly7 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.
source to share
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".
source to share