【问题标题】:Use regex to extract characters after a substring in python在python中使用正则表达式提取子字符串后的字符
【发布时间】: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


【解决方案1】:

这不是一个非常通用的解决方案,但它适用于您的字符串。

my_str = 'during the day, the color of the sky is blue. at sunset, the color of the sky is orange.'
r = re.compile('sky is [a-z]+')
out = [x.split()[-1] for x in r.findall(my_str)]

【讨论】:

    【解决方案2】:

    在您的正则表达式模式中,您只捕获后面跟着空格的字符串,但是“橙色”后面跟着一个点“。”,这就是它没有被捕获的原因。
    你必须包括点“。”在你的模式中。

    p1 = re.compile(r"is (.+?)[ \.]", re.I)
    re.findall(p1,text)
    # ['blue', 'orange']
    

    演示:
    https://regex101.com/r/B8jhdF/2

    编辑:
    如果单词在句尾且后面没有点“.”,我建议这样做:

    text = 'during the day, the color of the sky is blue at sunset, the color of the sky is orange'
    p1 = re.compile(r"is (.+?)([ \.]|$)")
    found_patterns = re.findall(p1,text)
    [elt[0] for elt in found_patterns]
    # ['blue', 'orange']
    

    【讨论】:

    • 如果最后一个字符不是点空格,或者最后一个单词后面没有其他字符,这将失败。
    • 没错,但这些是他正在处理的案例(在他的问题中)
    • 非常感谢!但是如果在“橙色”之后没有任何内容,例如,文本是“白天,天空的颜色是蓝色的”。日落时,天空的颜色是橙色的”。那我应该怎么提取呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多