简体   繁体   中英

How to extract usernames from text in python?

So I have a message such as "Hey @richard01 what time are we meeting @freddy023?" and I need a function to get it to extract the usernames which are always marked by beginning with an @ symbol.

def get_username(message, position):

So, for example, the following code would output "freddy023"

get_username("Hey @richard01 what time are we meeting @freddy023?", 2)
    

You can use regex:

import re

test_string = "Hey @richard01 what time are we meeting @freddy023?"

usernames = re.findall("\B@\w+", test_string)

print(usernames)
# Prints: ['@richard01', '@freddy023']

Here the regex expression matches the @ symbol followed by 1 or more word characters (including numbers). The \B makes sure the @ doesn't appear halfway through a word (like in an email)

I highly recommend having a play around with regex to fully understand how this works, Regex101 is brilliant for this. You can see this regular expression in action here: https://regex101.com/r/BOwY5z/1

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