I want a regex that stops at a certain character or end of the line. I currently have:
x = re.findall(r'Food: (.*)\|', text)
which selects anything between "Food:" and "|". For adding end of the line, I tried:
x = re.findall(r'Food: (.*)\||$', text)
but this would return empty if the text was 'Food: is great'. How do I make this regex stop at "|" or end of line?
You can use negation based regex [^|]*
which means anything but pipe
:
>>> re.findall(r'Food: ([^|]*)', 'Food: is great|foo')
['is great']
>>> re.findall(r'Food: ([^|]*)', 'Food: is great')
['is great']
A simpler alternative solution:
def text_selector(string)
remove_pipe = string.split('|')[0]
remove_food_prefix = remove_pipe.split(':')[1].strip()
return remove_food_prefix
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.