在python中查找关键字后面的单词

Rya*_*yan 19 python regex keyword matching

我想找到关键字后面出现的单词(由我指定和搜索)并打印出结果.我知道我想使用正则表达式来做它,我也尝试过,像这样:

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()
Run Code Online (Sandbox Code Playgroud)

输出只是:

"is"
Run Code Online (Sandbox Code Playgroud)

但是我希望得到"名字"这个词之后的所有单词和标点符号.

Auf*_*ind 28

您可以(例如)将您的字符串str.partition(separator)以下内容分开,而不是使用正则表达式:

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'
Run Code Online (Sandbox Code Playgroud)

但是,你必须分别处理不必要的空格.


Dom*_*ane 11

你的例子不起作用,但我理解这个想法:

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"
Run Code Online (Sandbox Code Playgroud)

这将打印所有"名称"后直到行尾.


fra*_*sua 8

另一种选择...

   import re
   m = re.search('(?<=name)(.*)', s)
   print m.groups()
Run Code Online (Sandbox Code Playgroud)


Pet*_*nov 4

而不是"^name: (\w+)"使用:

"^name:(.*)"
Run Code Online (Sandbox Code Playgroud)