使用regex在字符串中查找特定模式

2024-10-03 15:23:07 发布

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

RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." 

@pastorjnelson Pastor JN, I have spoken to you before.  But, lol, you didnt know who I was.  Or maybe, I didnt know2026 

假设上面有两个字符串。我想使用Python regex从给定的行@中获取一个特定的字符串模式。我该怎么做? 第一个字符串的预期输出应为@Complex,第二个字符串的预期输出应为@pastorjnelson。你知道吗


Tags: the字符串youifisseasonfirstdirector
3条回答
import re
s = """RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." 
@pastorjnelson Pastor JN, I have spoken to you before.  But, lol, you didnt know who I was.  Or maybe, I didnt know2026 
"""

print re.findall("@\w+", s)

输出:

['@Complex', '@pastorjnelson']
import re
s = """RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." 
@pastorjnelson Pastor JN, I have spoken to you before.  But, lol, you didnt know who I was.  Or maybe, I didnt know2026 
"""

print re.findall("@\w+", s)

输出:

['@Complex', '@pastorjnelson']

@.+?\W匹配上述两个示例。你知道吗

@是文字@

.+?搜索至少一个非换行符的任意序列

\W匹配非字母数字字符。你知道吗

相关问题 更多 >