我如何获得重新模式作为python中的动态输入?

时间:2019-03-13 08:35:09

标签: python

我正在python中使用 re 模块进行某些正则表达式操作。当我在python程序中定义了要静态匹配的模式时,它可以正常工作。

例如,

import re
s="hi can you help me out"
pattern=r'[a-z ]*' #pattern that takes space and lower case letters only
i= re.fullmatch(pattern,s) #to check the entire string
print(i.string)


output:
hi can you help me out

现在让我来解决我面临的问题,如果我试图在运行时从用户那里获取输入模式,它将引发异常。这里是代码

import re
s="hi can you help me out"
pattern=input("Enter pattern:")
i= re.fullmatch(pattern,s)
print(i.string)

output:
Enter pattern:r'[a-z]*'
Exception has occurred: AttributeError
'NoneType' object has no attribute 'string'

希望有人帮我解决这个问题。

python版本:3.5

预先感谢

1 个答案:

答案 0 :(得分:2)

您只需要输入此部分[a-z ]*,而无需使用r字符串前缀:

Python 3.x

import re
s = "hi can you help me out"
pattern = input("Enter pattern:")
i = re.fullmatch(pattern,s)
print(i.string)

Python 2.x

import re
s = "hi can you help me out"
pattern = raw_input("Enter pattern:")   # since input() in python2.x is the same eval(raw_input()) which would return an int
i = re.fullmatch(pattern,s)
print(i.string)

输出

Enter pattern:[a-z ]*
hi can you help me out