如何将用户输入合并到regex中的lookahead和lookback断言中

2024-06-12 02:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将用户输入与regex中的lookahead/lookhind断言结合起来以获得单词的上下文

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

目前,我正在手动更改代码的这部分(?=autogenerated)以获得所需的术语,但我希望代码能够更灵活地接受任何用户输入


Tags: 代码用户inputres断言单词regexword
1条回答
网友
1楼 · 发布于 2024-06-12 02:50:52

您可以在以下位置格式化用户输入:

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

相关问题 更多 >