简体   繁体   English

字符串中任何位置至少 n 位的正则表达式?

[英]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.这样就会找到a1aa2a2等。

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.所以它应该为a2a2a2a2a2返回 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.

相关问题 至少匹配 m 个组中的 n 个的正则表达式 - Regular Expression matching at least n of m groups 不允许在字符串中的任何位置使用 '.'(dot)(正则表达式) - Do not allow '.'(dot) anywhere in a string (regular expression) 正则表达式,用于验证给定字符串中至少 n 个大写、小写、数字和特殊字符的字符串 - Regular expression to validate a string for at least n number of Upper case, Lower case , number and special characters in a given string 使用正则表达式匹配字符串中的数字和文本 - Matching digits and text in a string using regular expression 限制小数点前后&#39;n&#39;位的正则表达式 - Regular expression to restrict 'n' digits before and after decimal point 正则表达式以查找集合或范围中的所有字母是否在字符串中的任何位置 - Regular expression to find if all letters in a set or range exist anywhere in string 正则表达式以减少位数 - Regular expression to cut digits 测试字符串中n个小写字符的正则表达式? - A regular expression that tests for n lowercase characters in a string? 正则表达式,用于检查字符串中是否存在至少3个不同的字符 - Regular expression that checks for existence at least 3 different characters in a string 如何使用正则表达式验证密码是否允许至少4位数字和1个字符而没有特殊字符? - How to validate a password allows at least 4 digits and 1 character without special character using regular expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM