2014-06-30 18 views
0

所以我一直在Python學習正則表達式,我已經學會了相當不錯,還有一些我不明白。我有一個字符串列表。在這個列表中,一些以「什麼」開頭,一些以「如何」開頭,並且都以'?'結尾。我想要所有以'What'開頭的String列表的子字符串。找到2模式之間的字符串python

這是我試過的模式:

pat = 'what + \w + \w + \w + ?' 

但主要問題是詞之間是不固定的數量。有的有3個,有的甚至有11-12個,如果我在正則表達式中使用or子句或if子句,它將變成一個沒有結果的巨大模式。有關如何解決這類問題的任何建議?

回答

0

你不需要重新。

l = ["What blah foo?","What bar?","How blah foo?","How bar?"] 

print [x for x in l if x.startswith("What")] 

['What blah foo?', 'What bar?'] 

重新使用:

l = ["What blah foo?","And What bar?","what bar?","How blah foo?","How bar?","What other foo","How other foo"] 
for s in l: 
    check= re.findall("^What .*\?",s,re.IGNORECASE) # find string starting with "What/what" and ending with "?" 
    if check: 
     print check[0] 
What blah foo? 
what bar? 
+0

工程..!非常感謝! – user3772366

+0

不用擔心,不客氣 –

0

重新使用和列表理解另一種方式:[ '?什麼吧' '什麼?嗒嗒富',]

list = ["What blah foo?","what bar?","How blah foo?","How bar?","another What?", "some what"] 

print [x for x in list if re.match(r'^what.*?', x, re.I)] 

相關問題