如何在python中使用正则表达式捕捉两个单词之间的字符?

2024-05-20 11:12:14 发布

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

如何在python中使用正则表达式捕捉两个单词之间的字符串?另外,只返回出现在两个单词之间的第一个集合。在

例如,我想捕捉所有介于“Hi”和“Best”之间的单词

original_string=“text text words Hi there,我需要正则表达式的帮助,Best Chris more words Hi这不是我想要的,Best”

designed_string=“在这里,我需要使用正则表达式的帮助,”

我知道你用这个:(?s) (?<;=开始时间)。+?(?=结束交货),并根据需要更换起始交货地点和结束交货地点。在

到目前为止,我试图用search搜索这两个词:

 b = re.search("Hi(.*?)/Best", a)

Tags: 字符串textsearchstringmorehi单词交货
1条回答
网友
1楼 · 发布于 2024-05-20 11:12:14

您需要调用^{}方法来返回匹配的字符串:

>>> import re
>>> original_string = "text text words Hi there, I need help using regular expressions ,Best Chris more words Hi This is not what I want ,Best"
>>> desired_string = re.search("(?s)(?<=Hi).+?(?=Best)", original_string).group()
>>> desired_string
' there, I need help using regular expressions ,'
>>>

相关问题 更多 >