[英]Extract pattern of usernames from messages
我構建了一個 Discord py bot,它允許用戶跨服務器進行通信(即兩個用戶不必在同一台服務器上)。 它適用於用戶名簡單的用戶,例如littlefox#1234
或little_fox#1234
。
但是,當用戶名更復雜時,如little fox#1234
之類的空格會被難住。 機器人接受諸如!hello
、 !greet
、 !bye
等命令。我嘗試使用正則表達式,但這也不起作用:
import re
match = re.match(r"!\w( [a-z]*#[0-9]*)", '!hello little fox#1234')
print(match)
other_match = re.match(r"!\w( [a-z]*#[0-9]*)", '!hello little_fox#1234')
print(other_match)
然而,它不匹配任何東西。 兩者都返回None
。 我該怎么辦?
您可以使用
(?:!\w+\s+)?([\w\s]*#[0-9]*)
查看正則表達式演示
細節
(?:!\\w+\\s+)?
- 匹配 1 或 0 次重復的可選組
!
- 一個!
字符\\w+
- 1+ 個字字符\\s+
- 1+ 個空格([\\w\\s]*#[0-9]*)
- 第 1 組:零個或多個單詞或空格字符、 #
和 0+ 數字。 請注意,如果必須至少有 1 個字母和數字,請將*
替換為+
: (?:!\\w+\\s+)?([\\w\\s]+#[0-9]+)
。
請參閱Python 演示:
import re
rx = r"(?:!\w+\s+)?([\w\s]*#[0-9]*)"
ss = ["!hello little fox#1234", "little fox#1234"]
for s in ss:
m = re.match(rx, s)
if m:
print(m.group(1)) # The username is in Group 1
對於這兩個輸入,輸出都是little fox#1234
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.