Home > Back-end >  Find multiple patterns with regex
Find multiple patterns with regex

Time:01-28

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) 
print(cmd_search)
#The parameters for re.findall are not working

The message error is:

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

CodePudding user response:

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)

Output:

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 := re.search(r"/(plot|cmd|text|msg)", string):
  print("match =", m.group())

Output:

match = /plot

If the string will always start with a command (e.g. /plot, etc.) then can use the match() function which will match starting with the first character. The search() function will search for the regexp anywhere in the string.

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

CodePudding user response:

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

(ref: https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching)

def plot(args):
    print(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):
    print(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
  • Related