B4J Question [Solved] Regex for MQTT

madru

Active Member
Licensed User
Longtime User
Hi I try to map Wildcards in MQTT topics. The generated expression OK (was verified @ regex101) but I can't get it to work with the matcher....

any ideas?

THX

regex101 Match Info: Match 1
Full match 0-33 `house/ground/kitchen/light/status`
Group 1. 13-20 `kitchen`
Group 2. 27-33 `status`

B4X:
Sub Button1_Action
   
    Dim subscription,topic As String

    subscription = "house/ground/+/light/#"

    Dim TopicList As List
    TopicList.Initialize
    TopicList.AddAll(Array As String("house/ground/kitchen/light/status", _
                             "house/ground/hallway/light/on", _
                             "house/1st/kitchen/light/status", _
                             "house/ground/hallway/light/on", _
                             "house/ground/hallway/light/bulp/off"))

    For Each topic As String In TopicList
        Log(verifyTopic(topic,subscription))
    Next

End Sub

Sub verifyTopic(topic As String, subscription As String) As String
   
    Dim Matcher1 As Matcher

    Matcher1 = Regex.Matcher(CreateMatch(subscription), topic)
    If Matcher1.Find = True Then
        Return Matcher1.Match
    End If
   
End Sub

Sub CreateMatch(text As String) As String

    If text.Contains("+") Then
        Dim a As String  = (sf.Stuff(text,"([\w\.\-\$]+)","+"))
        a= Replace(a,"\/","\\/")
    End If

    If a.Contains("#") Then
        Dim a As String  = (sf.Stuff(a,"([\w\.\-\$]+(\/[\w\.\-\$]+)*)","#"))
    End If
    Return a'"/^"&a&"$/"
   
End Sub

Sub Replace( Text As String,Pattern As String, Replacement As String) As String
   
    Dim jo As JavaObject = Regex.Matcher(Pattern, Text)
    Return jo.RunMethod("replaceAll", Array(Replacement))
   
End Sub

updated code section to a working solution, have fun
 
Last edited:
Top