![](/img/trans.png)
[英]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.