[英]Regular expression for at least n digits anywhere in the string?
A regular expression for at least one digit in a string looks like this:字符串中至少一位数字的正则表达式如下所示:
(?=.*[0-9])
So that would find a1a
or a2a2
etc.这样就会找到a1a
或a2a2
等。
Suppose we wanted at least 2 digits in the string.假设我们希望字符串中至少有 2 个数字。 So it should return true for a2a2
or a2a2a2
, but a2
would not pass.所以它应该为a2a2
或a2a2a2
返回 true ,但a2
不会通过。
What would that regex look like?那个正则表达式会是什么样子?
You could use match
here with the regex pattern \d.*\d
:您可以在此处将match
与正则表达式模式\d.*\d
一起使用:
var inputs = ["a2", "a2a2", "a2a2a2"]; for (var i=0; i < inputs.length; ++i) { if (inputs[i].match(/\d.*\d/)) { console.log("MATCH => " + inputs[i]); } else { console.log("NO MATCH => " + inputs[i]); } }
We can also use a length assertion, after removing all non digits characters:在删除所有非数字字符后,我们还可以使用长度断言:
var inputs = ["a2", "a2a2", "a2a2a2"]; for (var i=0; i < inputs.length; ++i) { if (inputs[i].replace(/\D+/g, "").length >= 2) { console.log("MATCH => " + inputs[i]); } else { console.log("NO MATCH => " + inputs[i]); } }
You can use a quantifier.您可以使用量词。 For example:例如:
([a-z][0-9]){2,}
This says at least 2 occurrences of the pattern.这表示至少出现 2 次该模式。 See more here https://docs.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions在此处查看更多信息https://docs.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.