2016-08-02 57 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