MQTT topic match evaluation

6.5k views Asked by At

I'm implementing an Android application using Mqtt (Paho). I have some components where I have to compare generally the subscribed topic which includes wildcards with the acutal topic that a client has published to.

I just don't get my head around it and my "rudimentary" Regex-skills don't helpt either...

Is there a utility class in Paho/Java MQTT to see if

"SENSOR/TEMPERATURE/+/DEGREE/#/ID" (subscribed topic)

is applies to

"SENOR/TEMPERATURE/GARDEN/DEGREE/CELSIUS/ABOVEZERO/ID" (actual topic)?

Does somebody know what would be the best way to do that?

Thank you!

EDIT: Hi There - I think this should be the right

public static boolean compareTopic(final String actualTopic, final String subscribedTopic){

   return actualTopic.matches(subscribedTopic.replaceAll("\\+", "[^/]+").replaceAll("#", ".+"));
}
3

There are 3 answers

0
tmcclean On BEST ANSWER

Your solution should work so in the case of your example the regular expression would be

"SENSOR/TEMPERATURE/[^/]+/DEGREE/.+/ID"

A website like http://www.regexplanet.com/advanced/java/index.html is a very good resource for cases like this.

0
ralight On

There is an example of how to match an MQTT topic against a subscription in the mosquitto_topic_matches_sub() function in util_topic.c:

https://github.com/eclipse/mosquitto/blob/master/lib/util_topic.c

It seems straightforward enough, but there are gotchas to be dealt with so your simple regex doesn't quite do the job.

0
pstanton On

I've run a few tests and i think this works:

String topicExp = topicPattern//
        .replaceAll("\\$", "\\\\\\$")//
        .replaceAll("\\+", "[^/]+")//
        .replaceAll("/\\#$", "(\\$|/.+)");

Pattern pattern = Pattern.compile(topicExp);
boolean match = pattern.matcher(topic).matches();
return match;