text = "This text is not important but name of teacher, name of dog and name of cat is very interesting"
Run Code Online (Sandbox Code Playgroud)
我需要在列表中添加"name of"旁边的单词
match = [teacher, dog, cat]
Run Code Online (Sandbox Code Playgroud)
re.findall从re模块中使用(import re第一个):
In [1033]: re.findall('(?<=name of )\w+', text)
Out[1033]: ['teacher', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)
'(?<=name of )\w+'
Run Code Online (Sandbox Code Playgroud)
使用固定宽度的lookbehind,提取后面的文本'name of '.
或者,一个稍微更具防弹性的正则表达式是:( '(?:name\s+of\s+)(\w+)'考虑到不同的空格字符).