如何连同前瞻/向后断言结合用户输入的正则表达式来获得这个词的背景下?
user_term = input('Enter a term: ')
word = 'Hello, this is an autogenerated message. Do not reply'
res_bef = re.search('(\w+-?,?.?\s){3}(?=autogenerated)', word)
print(res_bef.group(0))
目前,我手动更改了这部分代码(?=自动生成)来得到我想要的条件,但我想要的代码更加灵活采取任何用户输入。
您可以格式化用户输入:
user_term = input('Enter a term: ')
word = 'Hello, this is an autogenerated message. Do not reply'
res_bef = re.search(r'(\w+-?,?.?\s){{3}}(?={user})'.format(user=user_term), word)
print(res_bef.group(0))