【发布时间】:2020-07-03 14:58:45
【问题描述】:
我有一个看起来像这样的字符串 -
text = 'during the day, the color of the sky is blue. at sunset, the color of the sky is orange.'
我需要提取特定子字符串之后的单词,在本例中为“sky is”。也就是说,我想要一个给我这个的列表-
['blue', 'orange']
我已经尝试了以下 -
p1 =re.compile(r"is (.+?) ",re.I)
re.findall(p1,text)
但这只会给出输出
['blue']
但是,如果我的文字是
text = 'during the day, the color of the sky is blue at sunset, the color of the sky is orange or yellow.'
然后我跑
p1 = re.compile(r"is (.+?) ",re.I)
re.findall(p1,text)
我得到的输出为 -
['blue', 'orange']
请帮忙!我是正则表达式的新手,我被卡住了!
【问题讨论】:
-
你在组后面匹配一个空格,这在正则表达式中是有意义的。蓝色后面有一个空格,第一个例子中橙色后面没有。见regex101.com/r/Zvtuyz/1
-
能否详细说明?
-
试试这个:
re.compile(r"is (.+?)( |\.)", re.I) -
如果您单击regex101.com/r/Zvtuyz/1,您将看到在第一个示例中,只有一个以绿色突出显示的匹配项,因为
sky is orange.以点结尾。如果您想匹配空格或点\bis (.+?)[ .]或仅匹配单个单词\bis (\w+)[ .] -
只要使用
re.findall(r'(?i)\bsky\s+is\s+(\w+)', text)
标签: python regex string extract python-re