Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match the routing key with binding pattern for RabbitMQ topic exchange using python regex?

I am basically working on RabbitMQ. I am writing a python code wherein I am trying to see if the routing key matches with the binding pattern in case of topic exchange. I came across this link- https://www.rabbitmq.com/tutorials/tutorial-five-java.html where it says- "However there are two important special cases for binding keys:

* (star) can substitute for exactly one word.

# (hash) can substitute for zero or more words.

So how do I match the routing key of message with binding pattern of queue? For example routing key of message is "my.routing.key" and the queue is bound to topic exchange with binding pattern - "my.#.*". In general, how do I match these string patterns for topic exchange, preferably I am looking to use python regex.

like image 947
shweta Avatar asked Oct 16 '25 04:10

shweta


1 Answers

This is an almost direct port of the node lib amqp-match:

import re

def amqp_match(key: str, pattern: str) -> bool:
    if key == pattern:
        return True
    replaced = pattern.replace(r'*', r'([^.]+)').replace(r'#', r'([^.]+.?)+')
    regex_string = f"^{replaced}$"
    match = re.search(regex_string, key)
    return match is not None
like image 58
Eivydas Vilčinskas Avatar answered Oct 17 '25 18:10

Eivydas Vilčinskas