问题描述
谁能告诉我如何用正则表达式匹配 1-17 之间的数字:
Can someone tell me how to match a number between 1-17 with a regex:
我试过 [1-9]|1[0-7] 但它匹配 18 中的 8,例如因为第一部分.
I tried [1-9]|1[0-7] but it matches 8 in the 18 for example because of the first part.
有什么想法吗?我不想有前导零.
Any ideas? I don't want to have leading zeros.
已
问题是我正在尝试验证英国邮政编码,例如:
The problem is I'm trying to validate a UK postcode like to start with:
KW1-17(可能是 KW1、KW2 到 KW17)……这只是外面的部分.邮政编码可能是 KW15 1BM 或 KW151BM 所以我不能只使用锚点来匹配整个字符串......它变得更加复杂.
KW1-17 (it could be KW1, KW2 up to KW17) ... and this is just the outward part. The postcode may be KW15 1BM or KW151BM so I can't just use anchors to match the whole string ... it becomes more complicated.
推荐答案
你需要在正则表达式周围放置锚点,否则它会匹配子字符串:
You need to put anchors around the regex or it will match substrings:
^(?:[2-9]|1[0-7]?)$
我还冒昧地让您的正则表达式更高效:
I've also taken the liberty to make your regex a bit more efficient:
这篇关于正则表达式编号范围 1-17的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!