简体   繁体   English

使用正则表达式查找多个模式

[英]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.最终,我希望能够检测到命令(/text、/msg 等)并运行与之关联的 function。

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'

You can use OR condition with "|"您可以将 OR 条件与“|”一起使用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: 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.如果该术语只能出现一次,则可以使用“search()”并在在目标字符串中找到其中一个术语时停止。

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

Output: Output:

match = /plot

If the string will always start with a command (eg /plot, etc.) then can use the match() function which will match starting with the first character.如果字符串总是以命令开头(例如 /plot 等),则可以使用match() function,它将从第一个字符开始匹配。 The search() function will search for the regexp anywhere in the string. search() function 将在字符串中的任何位置搜索正则表达式。

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

If you're using a recent version of Python, you may be able to use match to solve your problem as an alternative:如果您使用的是 Python 的最新版本,您可以使用match作为替代方法来解决您的问题:

(ref: https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching ) (参考: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM