overlord9314
overlord9314

Reputation: 35

Creating a Java regular expression that will match on numbers at beginning of the input only

I have two regular expressions, one for US Passport and one for UK Passport.

UK : (?<!\B)(?:\d{9})(?!\B)
US : (?<!\B)(?=(?:[0][0-9]|1[0-5])|15|17|20|21|22|30|31|40|50|53)\d{9}(?!\B)

These were given to me and seem to work fine on their own examples..

The issue is that when inputting US Bank Routing Numbers in this format

Routing:121181976

and running a match in the system, the Routing number is identified as US/UK passport as well as Bank Routing Number(which has another, not relevant regex).

The Passport regexes are picking up the 9 digit Routing number despite the preceding text.

How can I change the Passport regexes so that they disregard input that has text attached to the string. I'm assuming that the ^ caret has some role in it, creating the condition that the match has to start with the numerals themselves initially.

Been attempting to create a regex in the various regex testing sites as well as consulting a regex book.

Upvotes: 0

Views: 917

Answers (1)

karthik manchala
karthik manchala

Reputation: 13640

Yes.. you have to use start ^ and end $ anchors.. this will check for the pattern only in the input.. ignoring if any text is found:

UK : ^(?:\d{9})$
US : ^(?=(?:[0][0-9]|1[0-5])|15|17|20|21|22|30|31|40|50|53)\d{9}$

Upvotes: 1

Related Questions