2016-08-02 81 views
1

我有下面的正則表達式(此鏈接:get python dictionary from string containing key value pairs正則表達式查找單詞包括「 - 」

r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)" 

這裏的解釋是:

\b   # Start at a word boundary 
(\w+)  # Match and capture a single word (1+ alnum characters) 
\s*:\s*  # Match a colon, optionally surrounded by whitespace 
([^:]*)  # Match any number of non-colon characters 
(?=   # Make sure that we stop when the following can be matched: 
\s+\w+\s*: # the next dictionary key 
|   # or 
$   # the end of the string 
)   # End of lookahead 

我的問題是,當我的字符串的字與「 - 」之間,例如:movie-night,上述正則表達式不起作用,我認爲這是由於b(\w+)。我怎樣才能改變這個正則表達式來處理包含「 - 」的單詞?我試過b(\w+-)但它不起作用。感謝您的幫助提前。

+1

您可以試試'b([\ w - ] +)'。 – shantanoo

+0

你的例子中的冒號在哪裏?你的正則表達式似乎需要一個,不是? –

回答

1

你可以嘗試一些像這樣的:

r"\b([\w\-]+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)" 

注意[\w\-]+,允許符合兩個單詞字符和破折號。

爲了將來的可讀性,您可能還需要調查re.X/re.VERBOSE,這可以使正則表達式更具可讀性。

+2

最好在將來添加時避開連字符:''[\ w \ - ] +''' – Owen

+0

感謝Elizafox&Owen。它按預期工作! – Leo

相關問題