简体   繁体   中英

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.

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}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM