gpt4 book ai didi

python - 使用 python string.find() 函数在字符串中向后遍历

转载 作者:行者123 更新时间:2023-12-01 04:55:50 24 4
gpt4 key购买 nike

我有一个字符串

mystr = "My mail id is abcd1234@account.com and xzy1234@mailinglist.com"
index = mymail.find('@') #gives me index using which i can traverse further with the mail id

如何在不使用列表而仅使用查找的情况下仅获取@之前的单词(即abcd1234和xzy1234)和@之后的单词(即account.com和mailinglist.com)。

例如:

index = mymail.find('@')
res = mymail.find(' ',index)
mystr[index+1:res] gives me --> account.com

最佳答案

您可以使用re.findall函数如下所示,

>>> s = 'My mail id is abcd1234@account.com and xzy1234@mailinglist.com'

获取 @ 之前的单词,

>>> re.findall(r'\S+(?=@)', s)
['abcd1234', 'xzy1234']

获取 @ 之后的单词,

>>> re.findall(r'(?<=@)\S+', s)
['account.com', 'mailinglist.com']

\S+匹配一个或多个非空格字符。 (?=@)正向先行断言匹配项后面必须跟着 @象征。 (?<=@)正向回顾断言匹配之前必须有 @符号。

关于python - 使用 python string.find() 函数在字符串中向后遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27417209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com