Find multiple patterns with regex

For a given string, I would like to know if a pattern is identified in it. Ultimately, I want to be able to detect a command (/text, /msg etc.) and to run a function associated with it.

string = str("/plot banana 24/02/2021 KinoDerToten")
#In this example, I want to get the /plot tot be returned. 

cmd_search = re.findall(r"/plot", "/cmd", "/text", "/msg", string) 
#The parameters for re.findall are not working

The message error is:

TypeError: unsupported operand type(s) for &: 'str' and 'int'

You can use OR condition with "|" in your regular expression like this.

import re

string = "/plot banana 24/02/2021 KinoDerToten"

cmd_search = re.findall(r"/(plot|cmd|text|msg)", string) 
for s in cmd_search:
 print("match:", s)


match: plot

If the term can only appear once then can use "search()" and stop when one of the terms is found in the target string.

if m :="/(plot|cmd|text|msg)", string):
  print("match =",


match = /plot

If you're using a recent version of Python, you may be able to use match to solve your problem as an alternative:


def plot(args):

def msg(txt):
    print(f'send "{txt}" to somewhere')

def do(x):
    match x.split(maxsplit=1):
        case ["/plot", arg]: plot(arg)
        case ["/msg", arg]: msg(arg)

do("/plot banana 24/02/2021 KinoDerToten")
# prints banana 24/02/2021 KinoDerToten

do("/msg usera hello test")
# send "usera hello test" to somewhere

or (slightly) more complex matching:

def plot(args):

def msg(to, txt):
    print(f'send "{txt}" to {to}')

def do(x):
    match x.split():
        case ["/plot", *args]: plot(args)
        case ["/msg", to, *txt]: msg(to, ' '.join(txt))

do("/plot banana 24/02/2021 KinoDerToten")
# prints ['banana', '24/02/2021', 'KinoDerToten']

do("/msg usera hello test")
# prints send "hello test" to usera
Back to Top