在python中使用带有正则表达式的input()

时间:2010-09-19 15:27:12

标签: regex

是否可以使用带有正则表达式的input()

我写过这样的东西

import re
words = ['cats', 'cates', 'dog', 'ship']

for l in words:
   m = re.search( r'cat..', l)  
   if m:
      print l
   else:
      print 'none'

这将返回'cates'

但现在我希望能够在'input()'中使用我自己的m = re.search( r'cat..', l)

类似

import re
words = ['cats', 'cates', 'dog', 'ship']

target = input()

for l in words:
   m = re.search( r'target..', l)  
   if m:
      print l
   else:
      print 'none'

这当然不起作用(我知道它会搜索'target'这个词而不是input())。 有没有办法做到这一点,或者不是正则表达式而不是我的问题的解决方案?

1 个答案:

答案 0 :(得分:0)

您可以动态构建RegEx:

target = raw_input()   # use raw_input() to avoid automatically eval()-ing.
rx = re.compile(re.escape(target) + '..')
                       # use re.escape() to escape special characters.

for l in words:
   m = rx.search(l)

....

但是没有 RegEx:

也是可能的
target = raw_input()

for l in words:
   if l[:-2] == target:
     print l
   else:
     print 'none'