简体   繁体   中英

Regular Expression to validate multiple condition

I require to validate a string using javascript with multiple conditions. I am not sure how to do this using regular expressions.

I need to check if the string does not contain any of the following conditions

Condition 1 : String of any length beginning with 18XX or 1-8XX or 8XX, where X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 1800abc, 812abc-def, 1-805-999-9999

Condition 2 : The string beginning with NXX or 1NXX or 1-NXX followed by exactly seven numbers not including hyphens, where N is any number from 2 to 9 (both 2 and 9 being inclusive) and X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 12-999-9999, 19009998888, 1-212---1-2-3-4-5-6-7--

Condition 3 : The string beginning with XXXXX, where X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 20176, 90210-Melrose

you cannot have a single regex match all this, Er may be you can!! see below

try using these three for each condition, check for all three and pass only those that do not match any.

condition 1: ^1?-?8\\d{2}.*$

condition 2: remove all hypens first then match for ^1?[2-9]\\d{7}$

condition 3: ^\\d{5}.*$

hope this helps

EDIT

You may have a single regex that can match this. since - seems to be an optional character lets remove them first, but as pointed out by @nnnnn in the comments, lets first check if the string actually begins with a - if it does then the string passes validation without further checks. then you can string those three together with | form a single regex which you can check against

^1?8\\d{2}.*|1?[2-9]\\d{7}|\\d{5}.*

i removed -? from the first part since we've already removed all hypens.

You're probably looking for alternation: http://www.regular-expressions.info/alternation.html

To match digits, you can use the digits class \\d or just plain [0-9] .

For example for condition 1, you can attempt to match it with:

 /^18\d\d|1-8\d\d|8\d\d$/.test("1800")  == true
 /^18\d\d|1-8\d\d|8\d\d$/.test("1-800") == true
 /^18\d\d|1-8\d\d|8\d\d$/.test("812")   == true

Of course, you can get smart with optional items , and groups to come up with something like:

 /^(1-?)?8\d\d$/.test("1-800") == true

You can use a tool like RegexPal to experiment with regular expressions. I usually just play with it in the Chrome Developer Tools console.

Try to figure out the rest on your own. :)

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