Replace last comma in a string with something else - How?

Hi,

I am trying to replace the last comma in a string with an and, how can I do that ? I tried to use .replaceLast but it seems that is not available in OpenHab. Everything else in the rule works perfectly fine.

if(Fensterabfrage.state == ON){
            Fensterabfrage.postUpdate(OFF)
            val OffeneFenster = Fenster.members.filter[ i | i.state.toString == "OPEN" ].map[ label ].reduce[ s, label | s + ", " + label ]
            OffeneFenster = OffeneFenster.replaceLast(", ", "und ")
            val String sourceRoomFensterabfrage = triggeringItem.name.split("_").get(0) 
            logInfo("Alexa Specific Rules","SourceRoom " + sourceRoomFensterabfrage)
            val String DestinationRoomFensterabfrage = sourceRoomFensterabfrage + "_Sprich"
            logInfo("Alexa Specific Rules","DestinationRoom " + DestinationRoomFensterabfrage)
            if (Fenster.members.filter[ i | i.state.toString == "OPEN" ].size > 0) {
                DestinationRoomFensterabfrage.sendCommand('<speak>Folgende Fenster sind offen: ' + OffeneFenster + '.</speak>')
            }
            else {
                DestinationRoomFensterabfrage.sendCommand('<speak>Alle Fenster sind geschlossen.</speak>')
            }

What other approaches are there to replace the last , with something else?

I think this Regex should work to replace the last comma with an “and”. But I am not sure how to correctly use it inside of an openhab rule:

This matches the last comma

/,(?=[^,]*$)/

Got it working:

val buildString = Fenster.members.filter[ i | i.state.toString == "OPEN" ].map[ label ].reduce[ s, label | s + ", " + label ]
val OffeneFenster = buildString.substring(0, buildString.lastIndexOf(',')) + ' und' + buildString.substring(buildString.lastIndexOf(',') + 1)

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.