[英]How do I write javascript Regex in such way it accepts 6 Characters
Javascript正则表达式验证它包含6个字符,其中一个字符(1)应该是一个数字。
var pwdregex =/^[A-Za-z1-9]{6}$/;
This will guarantee exactly one number (ie a non-zero decimal digit): 这将保证一个数字(即非零十进制数字):
var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9][A-Za-z]*$/;
And this will guarantee one or more consecutive number: 这将保证一个或多个连续数字:
var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9]+[A-Za-z]*$/;
And this will guarantee one or more not-necessarily-consecutive number: 这将保证一个或多个不一定连续的数字:
var pwdregex = /^(?=.{6}$)[A-Za-z]*(?:[1-9][A-Za-z]*)+$/;
All of the above expressions require exactly six characters total. 所有上述表达式总共需要六个字符。 If the requirement is six or more characters, change the
{6}
to {6,}
(or remove the $
from {6}$
). 如果要求是六个或更多个字符,改变
{6}
到{6,}
或删除$
从{6}$
)。
All possible combinations of 1 digit and alphanumeric chars with a length of 6. 所有可能的1位数字和字母数字字符组合,长度为6。
if (subject.match(/^[a-z]{0,5}\d[a-z]{0,5}$/i) && subject.length == 6) {
// Successful match
} else {
// Match attempt failed
}
[Edit] Fixed obvious bug... [编辑]修正了明显的bug ...
If you are ok with using a function instead of a regex you can do this: 如果您可以使用函数而不是正则表达式,则可以执行以下操作:
var sixAlphaOneDigit = function(s) {
return !!((s.length==6) && s.replace(/\d/,'').match(/^[A-Za-z]{5}$/));
};
sixAlphaOneDigit('1ABCDE'); // => true
sixAlphaOneDigit('ABC1DE'); // => true
sixAlphaOneDigit('ABCDE1'); // => true
sixAlphaOneDigit('ABCDE'); // => false
sixAlphaOneDigit('ABCDEF'); // => false
sixAlphaOneDigit('ABCDEFG'); // => false
If you want to do it strictly in a regex then you could build a terribly long pattern which enumerates all possibilities of the position of the digit and the surrounding (or leading, or following) characters. 如果你想在正则表达式中严格执行,那么你可以构建一个非常长的模式,它列举了数字位置和周围(或前导或后续)字符的所有可能性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.