Finding words after keyword in python

105,389

Solution 1

Instead of using regexes you could just (for example) separate your string with str.partition(separator) like this:

mystring =  "hi my name is ryan, and i am new to python and would like to learn more"
keyword = 'name'
before_keyword, keyword, after_keyword = mystring.partition(keyword)
>>> before_keyword
'hi my '
>>> keyword
'name'
>>> after_keyword
' is ryan, and i am new to python and would like to learn more'

You have to deal with the needless whitespaces separately, though.

Solution 2

Your example will not work, but as I understand the idea:

regexp = re.compile("name(.*)$")
print regexp.search(s).group(1)
# prints " is ryan, and i am new to python and would like to learn more"

This will print all after "name" and till end of the line.

Solution 3

An other alternative...

   import re
   m = re.search('(?<=name)(.*)', s)
   print m.groups()

Solution 4

Instead of "^name: (\w+)" use:

"^name:(.*)"

Solution 5

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.group(1)
Share:
105,389
Ryan
Author by

Ryan

Updated on May 22, 2020

Comments

  • Ryan
    Ryan about 4 years

    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".