我想在特定单词之后提取单词。例如,对于 txt = 'I like to eat apple. Me too.'
,我想提取 apple 之后的所有单词,即 '.我也是。'
我试过了
re.findall(r"(apple[^.]*\.)",txt)
但它返回到 'apple.'
我也试过
`re.findall(r"([^.]*?apple[^.]*\.)",txt)`
它返回到 'I like to eat apple.'
答案 0 :(得分:4)
你不需要正则表达式。只需使用 split
txt = 'I like to eat apple. Me too.'
print(txt.split("apple")[1])
输出
. Me too.
答案 1 :(得分:2)
如果您想使用 RegEx 解决此问题,您可以使用lookbehind: (?<=...) with 'apple' 替换点,然后匹配它后面的所有内容。
txt = 'I like to eat apple. Me too.'
re.findall(r"(?<=apple).*", txt);
它的作用是匹配前面有 reg.exp 的所有内容 (.*)。 苹果。
答案 2 :(得分:0)
def findAfter (text, after):
start = text.find (after) #Sets start to the start of keyword
end = start + len (after) #Sets end to the end of the keyword
return text [end : ] #Returns everything from the of the keyword
在您的示例中:
txt = 'I like to eat apple. Me too.'
keyword = 'apple'
findAfter (txt, keyword)
经过测试并为我工作。有不清楚的可以评论。