如何将477xx与正则表达式匹配

use*_*188 0 python regex

输入字符串必须是格式"477xx",其中x可能是0- 9或空格,长度值为5.我想找到具有正则表达式的以下目标.

["477  ", "4770 ", "4771 ", "4781 "]
Run Code Online (Sandbox Code Playgroud)

我该怎么做?这是我的粗略想法:"477[0,1,8,9]?"

Wik*_*żew 6

您可以使用以下正则表达式:

 ^477[0-9\s]{2}$
Run Code Online (Sandbox Code Playgroud)

请注意"4781"不匹配,因为它不以"477"开头.

这是演示.

以及Tutorialspoint上的示例代码:

p = re.compile(ur'^477[0-9\s]{2}$', re.MULTILINE)
test_str = u"477  \n4770 \n4771 \n4781 "
arr = re.findall(p, test_str)
print  arr
Run Code Online (Sandbox Code Playgroud)