如何将用户输入到前瞻和正则表达式向后断言

问题描述 投票:0回答:1

如何连同前瞻/向后断言结合用户输入的正则表达式来获得这个词的背景下?

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))

目前,我手动更改了这部分代码(?=自动生成)来得到我想要的条件,但我想要的代码更加灵活采取任何用户输入。

python regex text user-input text-mining
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.