简体   繁体   English

javascript 正则表达式测试仅适用于 6 位数字。 逗号分隔

[英]javascript regular expression test for 6 digit numbers only. comma seperated

and so this must pass:所以这必须通过:

454555, 939999 , 019999    ,727663

its for a user entering 6 digit invoice numbers.它适用于输入 6 位发票编号的用户。 it should fail if a number is 5 or 7 digit and not 6. so 1234567, 123456 should fail, as one set is more than 6 numbers.如果数字是 5 或 7 位而不是 6 1234567, 123456它应该会失败。所以1234567, 123456应该会失败,因为一组超过 6 个数字。

So far I have :到目前为止我有:

[0-9]{6}(\s*,*,\s*[0-9]{6})*

which only draw back is that it accepts 7 or more digit numbers.唯一的缺点是它接受 7 位或更多位数字。 cant figure out if its even possible at this point to do both, test for 6 digits separated by a comma and one or more space, and all the digits have to be only 6 digits and fail if one is not.无法弄清楚此时是否可以同时执行这两项操作,测试由逗号和一个或多个空格分隔的 6 位数字,并且所有数字必须只有 6 位,如果不是,则失败。

any help appreciated.任何帮助表示赞赏。 regular expressions are not my forte.正则表达式不是我的强项。

thanks谢谢

Norman诺曼

You can write it using regex like the function below.您可以像下面的函数一样使用正则表达式编写它。

const isPassword = (password: string) => /^\d{6}$/gm.test(password);

And here is an example test file below.这是下面的示例测试文件。

  test('should recognize a valid password', () => {
    expect(isPassword('123456')).toBe(true);
    expect(isPassword('000000')).toBe(true);
  });

  test('should recognize an invalid password', () => {
    expect(isPassword('asdasda1234')).toBe(false);
    expect(isPassword('1234567')).toBe(false);
    expect(isPassword('a123456a')).toBe(false);
    expect(isPassword('11.11.11')).toBe(false);
    expect(isPassword('aaaaaa')).toBe(false);
    expect(isPassword('eeeeee')).toBe(false);
    expect(isPassword('......')).toBe(false);
    expect(isPassword('werwerwerwr')).toBe(false);
  });

Your regex does not match 7 digits in a row, but it also doesn't enforce that it matches the whole string.您的正则表达式没有连续匹配7位数字,但它也没有强制要求匹配整个字符串。 It just has to match some substring in the string, so it would also match each of these:它只需要匹配字符串中的一些子字符串,所以它也会匹配这些中的每一个:

"1234512345612345612345"
"NaNaNaN  123456,    123456 BOOO!"
"!@#$%^&*({123456})*&^%$#@!"

Just add the start of string ( ^ ) and end of string ( $ ) anchors to enforce that the whole string matches and it will work correctly:只需添加字符串的开头 ( ^ ) 和字符串的结尾 ( $ ) 锚点以强制整个字符串匹配,它就会正常工作:

^[0-9]{6}(\s*,*,\s*[0-9]{6})*$

Also note that ,*, could be shortened to ,+ , and if you only want one comma in a row, just use , , not ,* or ,+ .另请注意, ,*,可以缩写为,+ ,如果您只想要一行中的一个逗号,只需使用, ,而不是,*,+

You can also replace [0-9] with \\d :您还可以用\\d替换[0-9]

^\d{6}(\s*,\s*\d{6})*$

In order to validate the full string you can use this regex.为了验证完整的字符串,您可以使用此正则表达式。

^(\s*\d{6}\s*)(,\s*\d{6}\s*)*,?\s*$

It works with six digits only, and you have to enter at least one 6 digit number.它仅适用于六位数字,您必须输入至少一个 6 位数字。 It also works if you have a trailing comma with whitespaces.如果您有一个带空格的尾随逗号,它也适用。

It's accepting more than six digit numbers because you're not anchoring the text, and for some odd reason you're optionally repeating the comma.它接受超过六位数的数字,因为您没有锚定文本,并且出于某些奇怪的原因,您可以选择重复逗号。 Try something like this:尝试这样的事情:

^[0-9]{6}(?:\s*,\s*[0-9]{6})*$

Also note that [0-9] is equivalent to \\d , so this can be rewritten more concisely as:另请注意, [0-9]等价于\\d ,因此可以更简洁地重写为:

^\d{6}(?:\s*,\s*\d{6})*$

Using only regex:仅使用正则表达式:

var commaSeparatedSixDigits = /^(?:\d{6}\s*,\s*)*\d{6}$/;
if (myInput.test(commaSeparatedSixDigits)) console.log( "Is good!" );

This says:这说:

  • ^ - Starting at the beginning of the string ^ - 从字符串的开头开始
  • (?:…)* - Find zero or more of the following: (?:…)* - 找到以下零个或多个:
    • \\d{6} - six digits \\d{6} - 六位数
    • \\s* - maybe some whitespace \\s* - 也许是一些空格
    • , - a literal comma , - 文字逗号
    • \\s* - maybe some whitespace \\s* - 也许是一些空格
  • \\d{6} - Followed by six digits \\d{6} - 后跟六位数字
  • $ - Followed by the end of the string $ - 后跟字符串的结尾

Alternatively:或者:

var commaSeparatedSixDigits = /^\s*\d{6}(?:\s*,\s*\d{6})*\s*$/;

I leave it as an exercise to you to decipher what's different about this.我把它作为一个练习,让你破译这有什么不同。


Using JavaScript + regex:使用 JavaScript + 正则表达式:

function isOnlyCommaSeparatedSixDigitNumbers( str ){
  var parts = srt.split(/\s*,\s*/);
  for (var i=parts.length;i--;){
    // Ensure that each part is exactly six digit characters
    if (! /^\d{6}$/.test(parts[i])) return false;
  }
  return true;
}

There isn;t any real need for a regexp.没有任何真正需要正则表达式。 Limit the input to only 6 characters, only accept numbers and ensure that the input has 6 digits (not show here).将输入限制为仅 6 个字符,只接受数字并确保输入有 6 位数字(此处未显示)。 So you would need:所以你需要:

HTML HTML

<input type='text' name='invoice' size='10' maxlength='6' value='' onkeypress='evNumersOnly(event);'>

JavaScript JavaScript

<script>
function evNumbersOnly( evt ) {
  //---  only accepts numbers
  //--- this handles incompatabilities between browsers
  var theEvent = evt || window.event;
  //--- this handles incompatabilities between browsers
  var key = theEvent.keyCode || theEvent.which;
  //--- convert key number to a letter
  key = String.fromCharCode( key );
  var regex = /[0-9]/;      // Allowable characters 0-9.+-,
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    //--- this prevents the character from being displayed
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}
</script>

I see a lot of complication here.我在这里看到了很多复杂性。 Sounds to me like what you want is pretty simple:听起来你想要的东西很简单:

/^(\d{6},)*\d{6}$/

Then we account for whitespace:然后我们考虑空格:

/^\s*(\d{6}\s*,\s*)*\d{6}\s*$/

But as others have noted, this is actually quite simple in JavaScript without using regex:但正如其他人所指出的,这在 JavaScript 中实际上非常简单,无需使用正则表达式:

function check(input) {
    var parts = input.split(',');
    for (var i = 0, n = parts.length; i < n; i++) {
        if (isNaN(+parts[i].trim())) {
            return false;
        }
    }
    return true;
}

Tested in the Chrome JavaScript console.在 Chrome JavaScript 控制台中测试。

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

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