我必须编写一个可检测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
以此类推...你有主意吗?
有人可以帮助我使用正则表达式吗?
答案 0 :(得分:3)
您可以尝试使用此模式:
\b(\d{6}|\d{9})\b
答案 1 :(得分:3)
或另一个:
\b\d{6}(?:\d{3})?\b
\b
与word boundary匹配\d{6}
六位数字(\d
是short的数字)(?:\d{3})?
和optional non capturing group包含另外三个数字答案 2 :(得分:2)
如果应该匹配ID部分,则可以使用一个替代来匹配6或9位数字。
使用锚点来声明字符串的开头^
和结尾$
,或在模式的开头和结尾添加单词边界\b
。
数字在第一个捕获组中。
^ID (\d{6}|\d{9})$