-1
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 

Suppose I have two strings shown above. I want to fetch a specific string pattern from a given line @____ using Python regex. How can I do that? The expected output should be @Complex for the first string and @pastorjnelson for the second string.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
stephen
  • 1
  • 4

2 Answers2

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)

Output:

['@Complex', '@pastorjnelson']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • When I do this it gives me like [u'@Complex'] and [u'@pastorjnelson'] in return. I want just text like @Complex – stephen Feb 28 '18 at 16:27
  • the snippet is returning you a list. You can access your required element using index 0. EX: print re.findall("@\w+", s)[0] – Rakesh Feb 28 '18 at 16:29
  • I have two different string. So I think it won't return list in my case. – stephen Feb 28 '18 at 16:36
0

@.+?\W matches both of the above examples.

@ is the literal @

.+? searches for an arbitrary sequence of at least one non-line break characters

\W matches a non-alphanumeric character.

ACascarino
  • 4,340
  • 1
  • 13
  • 16