gpt4 book ai didi

python - 从消息中提取用户名模式

转载 作者:行者123 更新时间:2023-12-01 08:14:03 24 4
gpt4 key购买 nike

我构建了一个 Discord py 机器人,允许用户跨服务器进行通信(即两个用户不必位于同一服务器上)。它适用于具有简单用户名的用户,例如 littlefox#1234little_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]*)

请参阅regex demo

详细信息

  • (?:!\w+\s+)? - 匹配 1 或 0 次重复的可选组
    • ! - 一个 ! 字符
    • \w+ - 1+ 个单词字符
    • \s+ - 1 个以上空格
  • ([\w\s]*#[0-9]*) - 第 1 组:零个或多个单词或空白字符、# 和 0+ 数字.

请注意,如果必须至少有 1 个字母和数字,请将 * 替换为 +: (?:!\w+\s+)?([\w\s]+#[0-9]+)

请参阅Python demo :

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

关于python - 从消息中提取用户名模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com