首页 > 解决方案 > 如何使用正则表达式提取所有使用Python的特定模式之间的单词

问题描述

df['text'][0] = 'beautiful place\nlocation: United States Of America\ntraveldate:'

我需要在“位置”之后和\n字符之前提取所有单词。

我在下面的代码中尝试了正则表达式模式:

def Location(txt):
    txt1 = re.findall(r"(location:\s[A-Z]\w+)", txt)
    return txt1
df['Location'] = df['text'].apply(lambda x : Location(x))

实际输出:['location: United']

预期输出:'United States Of America'

标签: regex

解决方案


str.replace与捕获组一起使用:

df['Location'] = df['text'].str
    .replace(r'^.*\blocation:\s*([^\n]+).*$', r'\1', flags=re.DOTALL)

推荐阅读