正则表达式-6位或9位以上或更少或更多之间的表达式

时间:2019-06-12 15:18:59

标签: regex

我必须编写一个可检测6位数或9位数的正则表达式-含义:

ID 123 - it should not meet the regext as it is 3 digits
ID 1234 - it should not meet the regext as it is 4 digits
ID 12345 - it should not meet the regext as it is 5 digits
ID 123456 - it should meet the regex it is 6 digits <==========
ID 1234567 - it should not meet the regext as it is 7 digits
ID 12345678 - it should not meet the regext as it is 8 digits
ID 123456789 - it should meet the regext as it is 9 digits <==========
ID 1234567890 - it should not meet the regext as it is 10 digits
ID 12345678901 - it should not meet the regext as it is 11 digits

以此类推...你有主意吗?

有人可以帮助我使用正则表达式吗?

3 个答案:

答案 0 :(得分:3)

您可以尝试使用此模式:

\b(\d{6}|\d{9})\b

答案 1 :(得分:3)

或另一个:

\b\d{6}(?:\d{3})?\b

See demo at regex101

答案 2 :(得分:2)

如果应该匹配ID部分,则可以使用一个替代来匹配6或9位数字。

使用锚点来声明字符串的开头^和结尾$,或在模式的开头和结尾添加单词边界\b

数字在第一个捕获组中。

^ID (\d{6}|\d{9})$