簡體   English   中英

如何從 python 中的文本中提取用戶名?

[英]How to extract usernames from text in python?

所以我有一條消息,例如“嘿@richard01 我們什么時候見面@freddy023?” 我需要一個 function 來提取始終以@符號開頭的用戶名。

def get_username(message, position):

因此,例如,以下代碼將 output "freddy023"

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

您可以使用正則表達式:

import re

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

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

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

此處的正則表達式匹配@符號后跟 1 個或多個單詞字符(包括數字)。 \B確保@不會出現在單詞中間(如在電子郵件中)

我強烈建議使用正則表達式來充分了解它是如何工作的,Regex101 非常適合這一點。 您可以在此處查看此正則表達式: https://regex101.com/r/BOwY5z/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM