Question

So what i am trying to do is to have an input field named a. Then have a line of regex which checks a for 'i am (something)' (note something could be a chain of words.) and then prints How long have you been (something)?

This is my code so far:

if re.findall(r"i am", a):
    print('How long have you been {}'.format(re.findall(r"i am", a)))

But this returns me a list of [i, am] not the (something). How do i get it to return me (something?)

Thanks,

A n00b at Python

Was it helpful?

Solution

Do you mean something like this?

>>> import re
>>> a = "I am a programmer"
>>> reg = re.compile(r'I am (.*?)$')
>>> print('How long have you been {}'.format(*reg.findall(a)))
How long have you been a programmer

r'I am (.*?)$' matches I am and then everything else to the end of the string.


To match one word after, you can do:

>>> a = "I am an apple"
>>> reg = re.compile(r'I am (\w+).*?$')
>>> print('How long have you been {}'.format(*reg.findall(a)))
How long have you been an

OTHER TIPS

may be just a simple solution avoiding a weigth and cost regexp

>>> a = "i am foxmask"
>>> print a[5:]
foxmask
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top