Homan Mohammadi
Homan Mohammadi

Reputation: 55

Python regex for string up to character or end of line

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?

Upvotes: 3

Views: 5502

Answers (2)

kylieCatt
kylieCatt

Reputation: 11049

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

Upvotes: 0

anubhava
anubhava

Reputation: 786081

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']

Upvotes: 6

Related Questions