简体   繁体   English

正则表达式只允许9或10个字符?

[英]Regex to allow only 9 or 10 characters?

9 characters requires 2 letters in the beginning ie ab1234567 and 10 characters needs to have all digits i,e 1234567890. How do I do this using regex? 9个字符在开头需要2个字母,即ab1234567和10个字符需要所有数字i,e 1234567890.如何使用正则表达式执行此操作?

Here is what I have tried. 这是我尝试过的。

/^[a-zA-Z]{2}[\d]{7}|[\d]{10}$/

This doesnt seem to work. 这似乎不起作用。 I would greatly appreciate your help. 非常感谢你的帮助。

The | | in your regex allows it to match either of these two possibilities: 在你的正则表达式允许它匹配这两种可能性中的任何一种:

^[a-zA-Z]{2}[\d]{7}

[\d]{10}$

That is, start of string then 2 letters and seven numbers followed by anything, or anything followed by 10 numbers and end of string. 也就是说,字符串的开头然后是2个字母和7个数字,后跟任何东西,或者后跟10个数字和字符串结尾的任何内容。 Try this: 尝试这个:

/^([a-zA-Z]{2}\d{7}|\d{10})$/

(Note also that I've removed the [] from around each \\d - there's no point having a character class with only one character in it.) (另请注意,我已经从每个\\d删除了[] - 没有必要让一个字符类只包含一个字符。)

The problem is that the ^ is only applying the first option, and the $ only applies to the second one. 问题是^仅应用第一个选项,而$仅适用于第二个选项。

Try this: 尝试这个:

/^(?:[a-z]{2}\d{7}|\d{10})$/i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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