我想要一个在特定字符或行尾停止的正则表达式。我目前有:
x = re.findall(r'Food: (.*)\|', text)
它会选择“Food:”和“|”之间的任何内容。为了添加行尾,我尝试了:
x = re.findall(r'Food: (.*)\||$', text)
但是如果文本是“Food: is great”,这将返回空。如何让这个正则表达式停在“|”还是行尾?
最佳答案
你可以使用基于否定的正则表达式 [^|]*
这意味着除 pipe
之外的任何东西:
>>> re.findall(r'Food: ([^|]*)', 'Food: is great|foo')
['is great']
>>> re.findall(r'Food: ([^|]*)', 'Food: is great')
['is great']
关于字符串的 Python 正则表达式到字符或行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35021796/