简体   繁体   English

为什么我的Javascript RegEx量词“不起作用”?

[英]Why is my Javascript RegEx quantifier “not working”?

This question seems to have such an easy answer and an ashaming one for me, that I hope you just comment, then I can delete the thread after solving. 这个问题似乎对我来说是一个简单的答案,令人感到羞愧,希望您能发表评论,然后在解决后删除该主题。 ;) ;)

I have a problem with the {n} quantifier in my RegEx. 我的RegEx中的{n}量词有问题。 It does not seem to work! 它似乎不起作用!

Here my code 这是我的代码

document.time.Id.onkeyup = function() {
  var that = this.value,
      regex = /^[1-9]{1}/
  if (that) {   
      if (!that.match(regex)) {
          this.nextSibling.innerHTML="Number must be between '1' and '100'.";
      } else {
          this.nextSibling.innerHTML="";
      }
  } else {
      this.nextSibling.innerHTML="";
  } 
}

As you can see, I want to match against 1 till 100 in the end, but I am stuck at the bit, that the quantifier does not work. 如您所见,我想最后与1到100进行匹配,但是我有点犹豫,即量化器不起作用。 When I key in 0 there is a match failure, as well with any letter...so it does work "a bit". 当我键入0时,匹配失败以及任何字母...因此它确实“有点”起作用。

Can you please help me? 你能帮我么?

Your regular expression says to match any string that starts (because it's anchored at the beginning using ^ ) with any digit between 1 and 9. This is why it doesn't match 0 or letters. 您的正则表达式说要匹配任何以1到9之间的任何数字开头的字符串(因为它以^开头)。这就是为什么它不匹配0或字母的原因。

A range validation is something you'd want to check using basic number comparisons: 您要使用基本数字比较来检查范围验证:

var numberValue = parseInt(this.value, 10);
if (numberValue >= 1 && numberValue <= 100) {
    // valid number
}

For the sake of completeness, you could create a regular expression for that purpose which I don't recommend, though : 为了完整起见,您可以为此目的创建一个正则表达式, 但我不建议这样做

^(?:[1-9][0-9]?|100)$

Try using this regex instead: 尝试改用此正则表达式:

^[1-9][0-9]?$|^100$

The quantifier you used is actually redundant, since [1-9] and [1-9]{1} mean the same thing. 您使用的量词实际上是多余的,因为[1-9][1-9]{1}含义相同。

If you input 1000 with your current code and regex, the number will pass because a match counts as long as the regex matches any part of the string. 如果您使用当前代码和正则表达式输入1000 ,则该数字将通过,因为只要正则表达式与字符串的任何部分匹配,匹配就算在内。 Using $ (end of line anchor) forces the regex to check the whole string. 使用$ (行锚)将强制正则表达式检查整个字符串。

But you should probably be using a simple if check for that. 但是您应该使用简单的if检查。

if (that > 0 && that <= 100 && that % 1 == 0) {
    ...
}

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

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