简体   繁体   中英

Everything after/before regex in Python

I have multiple instances of string with the next structure:

RT @username: Tweet text

I need to capture the username (to later construct a network). So far I have this:

re.findall('\@(.*)') 

which should get everything after '@', but I'm having a hard time figuring out how to get everything before (excluding) ':'.

To get everything between @ and : , you can use the pattern:

@([^:]+)

Below is a breakdown of what it matches:

@      # @
(      # The start of a capture group
[^:]+  # One or more characters that are not :
)      # The close of the capture group

And here is a demonstration:

>>> from re import findall
>>> mystr = '''\
... RT @username: Tweet text
... RT @abcde: Tweet text
... RT @vwxyz: Tweet text
... '''
>>> findall('@([^:]+)', mystr)
['username', 'abcde', 'vwxyz']
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM