简体   繁体   中英

Regular expression for numbers where the first digit depends on 4th and 5th digits

Not sure how to do the following with regex...
A nine digit number cannot start with 900-999 except for when the 4th and 5th digits are 70-88 or 90-99.

I have the following so far:

^9[0-9][0-9]

This just checks the first three digits and I am not sure how to incorporate the second condition.

Here is the regex that will find all nine digit numbers starting with 900 that match your conditions:

^9[0-9][0-9](7[0-9]|8[0-8]|9[0-9])[0-9]{4}

The second part of the above regex is an OR condition (using the | symbol) which matches the 70 - 79, 80 - 88, and 90 - 99 patterns. Test it on an online tester like http://regexpal.com/ to see how it works. If you want to exclude the invalid numbers you may have to alter the condition to look for the invalid numbers instead (eg those starting with 900 where the fourth digit is a six or less etc).

This should match the numbers you need:

^(?:9[0-9]{2}(?:[79][0-9]|8[0-8])[0-9]{4}|[0-8][0-9]{8})$

9[0-9]{2}(?:[79][0-9]|8[0-8])[0-9]{4} will match numbers that start with 9, and [0-8][0-9]{8} will match the rest. (not starting with 900-999 is the same as not starting with 9).
Example: http://rubular.com/r/6uVWC0cLgX

If your flavor supports it, you can simplify the pattern using a lookahead :

^(?:9(?=..(?!89)[7-9])|[0-8])[0-9]{8}$

The only trick here is on the first digit. It can match a nine followed by 2 digits and and a number between 70 and 99 (but not 89), and then 8 more digits.
Example: http://rubular.com/r/UVVkfJ3v3V

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