gpt4 book ai didi

python - 在特定字符后提取文本

转载 作者:太空狗 更新时间:2023-10-29 22:06:39 24 4
gpt4 key购买 nike

我需要提取@

后面的单词

我该怎么做?我正在尝试:

text="Hello there @bob !"
user=text[text.find("@")+1:]
print user

输出:

bob !

但正确的输出应该是:

bob

最佳答案

有趣的正则表达式解决方案:

>>> import re
>>> re.findall(r'@(\w+)', '@Hello there @bob @!')
['Hello', 'bob']
>>> re.findall(r'@(\w+)', 'Hello there bob !')
[]
>>> (re.findall(r'@(\w+)', 'Hello there @bob !') or None,)[0]
'bob'
>>> print (re.findall(r'@(\w+)', 'Hello there bob !') or None,)[0]
None

上面的正则表达式将选取一个或多个字母数字字符的模式,跟随一个“@”字符,直到找到一个非字母数字字符。

如果您想捕获更广泛的子字符串,这里有一个匹配一个或多个非空白字符的正则表达式解决方案:

>>> re.findall(r'@(\S+?)', '@Hello there @bob @!')
['Hello', 'bob', '!']

请注意,当上述正则表达式遇到类似 @xyz@abc 的字符串时,它将在一个结果中捕获 xyz@abc 而不是 xyzabc 分开。要解决这个问题,您可以使用否定的 \s 字符类,同时也否定 @ 字符:

>>> re.findall(r'@([^\s@]+)', '@xyz@abc some other stuff')
['xyz', 'abc']

这里有一个正则表达式解决方案,仅在您不需要任何数字或其他任何内容时才匹配一个或多个字母字符:

>>> re.findall(r'@([A-Za-z]+)', '@Hello there @bobv2.0 @!')
['Hello', 'bobv']

关于python - 在特定字符后提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836812/

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