[英]Regex match pattern into a characters string OR another pattern in the same characters string
[英]Regex to match pattern and also limit numer of characters
我在使用正则表达式匹配模式并限制字符数时遇到问题:
例如,我允许使用数字前缀: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60
那么我只想要数字,并且整个的最大长度等于 9。所以例如数字: 255555555
可以,但31555555555555555
不是。
这是我解决此问题的尝试,但它不应该起作用:
^( (2|31|32|35|37|38|39|41|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60)+[0-9]* ){9}$
使用正向前瞻来限制(但不匹配)前缀,然后精确匹配 9 位数字:
^(?=2|31|32|35|37|38|39|41|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60)\d{9}$
您可以先测试长度,然后测试前缀。
function check(s) { return /(?=^\\d{1,9}$)^(2|3[125-9]|4[16-9]|5.|60)/.test(s); } console.log(['255555555', '31555555555555555', '33', '5a', '5', '50'].map(check));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.