使用正则表达式在字符串中查找特定模式[复制]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

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正则表达式从给定的行@____获取特定的字符串模式。我怎样才能做到这一点?对于第一个字符串,预期输出应为@Complex,对于第二个字符串,应为@pastorjnelson。

python json regex
2个回答
0
投票
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']

0
投票

@.+?\W匹配上述两个例子。

@是文字@

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

\W匹配非字母数字字符。

© www.soinside.com 2019 - 2024. All rights reserved.