I want to find words that appear after a keyword (specified and searched by me) and print out the result. I know that i am suppose to use regex to do it, and i tried it out too, like this:
import re
s = "hi my name is ryan, and i am new to python and would like to learn more"
m = re.search("^name: (\w+)", s)
print m.groups()
The output is just:
"is"
But I want to get all the words and punctuations that comes after the word "name".
What you have used regarding your output:
What you have to use (match all):
Your example will not work, but as I understand the idea:
This will print all after "name" and till end of the line.
You could simply do
This will split your string and return a list like this ['hi my', 'is ryan, and i am new to python and would like to learn more']
depending on what you want to do this may help or not.
Without using regex, you can
strip punctuation (consider making everything single case, including search term)
split your text into individual words
find index of searched word
get word from array (
index + 1
for word after,index - 1
for word before )Code snippet:
For multiple occurences, you need to save multiple indices:
Instead of
"^name: (\w+)"
use: