Trying to find all matches in RegEx that say "I'm" but not at the end of a word

Viewed 224

I'm creating a sort of "Dad Joke" bot in discord.py, and I'm using RegEx to find all the "triggers" to start the dad joke. Here's my code so far:

            string = message.content.lower()
            pattern = ' im | i\'m | i am '

            result = re.split(pattern, string, 1)

            if len(result) == 2:
                if "botpuns" in result[1]:
                    await message.channel.send(f"No {message.author.mention}, I'm Botpuns!!")
                else:
                    await message.channel.send(f"Hi {result[1]}, I'm Botpuns!!")

            await bot.process_commands(message)
            return

Right now it works, but not exactly how I'd like it to. It works whenever someone says things like "im hungry", but it also works when someone says something like "him", since that meets the criteria too. I don't want to make it check if there's nothing directly behind it because then it wouldn't work at the beginning of a message, but I'm wondering if there's a way to just check if it ISN'T at the end of a word. Thanks!!

1 Answers

If I understand correctly from the comments, what you want is:

import re
txt = "Hi i'm dad"

message = re.match(r'^(.*[\s])?(im|i am|i\'m)[\s](.*)$', txt, re.IGNORECASE)
print(message.groups()[-1])
# prints the last group, which is "dad"

^(.*[\s])?(im|i am|i\'m)[\s](.*)$

  • (.*[\s])? - group 0(optional): any amount of characters and a single whitespace
  • (im|i am|i\'m)[\s] - group 1: im, i am, or i'm are flagged here, followed by a single whitespace
  • (.*) - group 2: any amount of characters.
Related