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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With