Python 如何匹配精确字符串和通配符字符串

Python 如何匹配精确字符串和通配符字符串,python,python-3.x,wildcard,string-matching,discord.py,Python,Python 3.x,Wildcard,String Matching,Discord.py,比如说,我有: import discord, asyncio, time client = discord.Client() @client.event async def on_message(message): if message.content.lower().startswith("!test"): await client.send_message(message.channel,'test') client.run('clienttokenhere'

比如说,我有:

import discord, asyncio, time

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith("!test"):
        await client.send_message(message.channel,'test')

client.run('clienttokenhere')
我想做两件事:

1) 使其成为当且仅当用户准确键入
!测试
和其他内容,它将在通道中打印出
test

2) 如果用户在
中键入!test
首先后跟空格
和至少一个其他字符串,它将打印出
test
——例如:a)
!测试将不会打印任何内容,b)
!test
!test
后跟一个空格)不会打印任何内容,c)
!test1将不打印任何内容,d)
!testabc
不会打印任何内容,但e)
!测试1将打印出
测试
,f)
!测试123abc将打印出
测试
,g)
!测试a
将打印出
测试
,h)
!考试?!abc123
将打印出
测试
,等等


我只知道
startswith
endswith
,就我的研究所知,没有确切的
这样的东西,我也不知道如何使它在
startswith

之后使用
=
操作符,它需要最少的字符数

1) 只有<代码>时打印测试!在收到的字符串中测试

if message.content.lower() == '!test':
    await client.send_message(message.channel,'test')
2) 打印
test
,后跟字符串(如果后跟字符串)

# If it starts with !test and a space, and the length of a list
# separated by a space containing only non-empty strings is larger than 1,
# print the string without the first word (which is !test)

if message.content.lower().startswith("!test ") 
   and len([x for x in message.content.lower().split(' ') if x]) > 1:
    await client.send_message(message.channel, 'test ' + ' '.join(message.content.split(' ')[1:]))

看起来您需要一个正则表达式,而不是
startswith()
。您似乎有两个相互冲突的要求:

1) 使其成为当且仅当用户准确键入
!测试
和其他内容,它将在通道中打印出
test

2a)
!测试
不会打印任何内容

包括1,不包括2a:

import re
test_re = re.compile(r"!test( \S+)?$")
# This says: look for
# !test (optionally followed by one space followed by one or more nonspace chars) followed by EOL
# 

@client.event
async def on_message(message):
    if test_re.match(message.content.lower()):
        await client.send_message(message.channel,'test')
包括2a,不包括1,替换此行(test
之后的空格和填充物不再是可选的):


可能重复的请不要破坏你的帖子。一旦您提交了一篇文章,您就已经将内容授权给了Stack Overflow社区(在CC by SA许可下)。如果您想取消此帖子与您的帐户的关联,请参阅?
test_re = re.compile(r"!test \S+$")