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

时间:2018-02-28 16:19:33

标签: python json regex

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。

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分:0)

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

@是文字@

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

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