Reputation: 1861
I'm trying to write a regex to parse a bank sort code from a database. The reason I need a regex is that the sort code might be contained in a sentence. But also, it might not be a sort code at all because the people entering data into the database some times put bank account numbers and phone numbers into the sort code column. I can use
^[^0-9]*[0-9]{6}[^\d]*$
which works on
"blah123456blah"
but not on
"Emloyee 12's srt code : 123456"
Anything else I've tried gives me a match for 6 or more digits within a string (which is then most likely a bank account number).
Any help is greatly appreciated.
Upvotes: 2
Views: 4689
Reputation: 626851
You say you are using
[0-9]{2}\s*-?\s*[0-9]{2}\s*-?\s*[0-9]{2}
To add the boundaries like you need, add (^|[^0-9])
(either the string start position (^
) or (|
) a non-digit ([^0-9]
)) in front and ([^0-9]|$)
(matching a non-digit or the end of string position ($
)) at the end:
(^|[^0-9])[0-9]{2}\s*-?\s*[0-9]{2}\s*-?\s*[0-9]{2}([^0-9]|$)
See the regex demo.
Upvotes: 2