2010-09-19 195 views
0

正則表達式輸入()是否有可能與正則表達式使用與蟒蛇

我已經寫了這樣的事情

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

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

這將返回使用輸入()「蓋茨」

但現在我希望能夠用我自己的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' 

這當然不起作用(我知道它會搜索「目標」一詞而不是輸入())。 有沒有辦法做到這一點或不是正則表達式不是我的問題的解決方案?

回答

0

你可以動態構建的正則表達式:

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) 

.... 

但也有可能不正則表達式

target = raw_input() 

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

確定這個工作,但就是這也可能與其他正則表達式模式+? 。 *^$()[] {} | \我如何找到所有以'ca'開頭的單詞。我理解這些模式是如何工作的,但我的問題是使它們與input()一起工作,以便用戶可以自己選擇他的輸入() Ps我不希望你做所有這些工作,但如果你可以直接我到一個網站或教程或任何可以幫助我... – Preys 2010-09-20 16:35:45

+0

@Preys:http://docs.python.org/library/stdtypes.html#str.startswith – kennytm 2010-09-20 17:23:15