简体   繁体   中英

Extract pattern of usernames from messages

I built a Discord py bot that allows users to communicate across servers (ie both users don't have to be on the same server). It works for those with simple usernames such as littlefox#1234 or little_fox#1234 .

However, when the username is more complex with spaces such as little fox#1234 it gets stumped. The bot accepts commands such as !hello , !greet , !bye etc. I tried using regex but that doesn't work either:

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)

However it does not match anything. Both return None . What do I do?

You may use

(?:!\w+\s+)?([\w\s]*#[0-9]*)

See the regex demo

Details

  • (?:!\\w+\\s+)? - an optional group matching 1 or 0 repetitions of
    • ! - a ! char
    • \\w+ - 1+ word chars
    • \\s+ - 1+ whitespaces
  • ([\\w\\s]*#[0-9]*) - Group 1: zero or more word or whitespace chars, # and 0+ digits.

Note that in case there must be at least 1 letter and digit replace * with + : (?:!\\w+\\s+)?([\\w\\s]+#[0-9]+) .

See the 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

For both inputs, the output is little fox#1234 .

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