[SOLVED] Extracting substringAfter in a Rule (OH2 vs OH3)

I use text configurations, not the UI.

In OH2 I used to get a substring of “sonoff_s26_0” with:

var SwitchRaw = Switch.substringAfter("_")

which would return “s26_0”, this is what I wanted.

This no longer works in OH3, how do I do the same thing in OH3?

EDIT: Here’s the whole Rule for context:

rule "Sonoff FW Info"
    when
        Time cron "0 */2 * * * ? *"
    then
                Switches.members.filter[i | i.name.contains("sonoff")].forEach[ SwitchItem sw |
                        var Switch = sw.name.substring(0)
// UPDATE "STATUS 2" COMMAND FOR EACH SWITCH
                        var SwitchRaw = Switch.substringAfter("_")

                        logInfo(SwitchRaw, PowerState)
                        logInfo("SwitchRaw", PowerState)        // NOT TRIGGERING
                        val mqttActions = getActions("mqtt","mqtt:broker:mosquitto") // change to your broker name!
                        mqttActions.publishMQTT("sonoff/" + SwitchRaw + "/cmnd/status","2")
                ]
end

see this thread: OH3 substringAfter is undefined for the type String

Yes I saw that before I posted this topict, but one shouldn’t have to write functions to achieve what was a one liner in OH2, if so that’s a major step backwards IMHO.

You could try to import org.apache.commons.lang.stringUtil within your rule.

1 Like

Thanks, just tried your suggestion, still getting same error:

 Script execution of rule with UID 'default-2' failed: 'substringAfter' is not a member of 'java.lang.String'; line 66, column 20, length 26 in default

I inseted this at top of rules file:

import org.apache.commons.lang.stringUtil

I‘m not at my computer atm, so cannot verify.
It might be StringUtil and the usage could then be StringUtil.substringAfter…

1 Like

Thanks for the help @hmerk I decided to go another (simpler for the moment) route using a Transform Map. There’s only 18 items to parse, and even though it seems to be repetitive, saves a lot of pain in the long run.

In Rule:

var SwitchRaw = transform("MAP", "sonoff.map", Switch)

Map File:

sonoff_s26_0=s26_0
sonoff_s26_1=s26_1
sonoff_s26_2=s26_2
sonoff_s26_3=s26_3
sonoff_s26_4=s26_4
sonoff_s26_5=s26_5
sonoff_s26_6=s26_6
sonoff_s26_7=s26_7
sonoff_s20_0=s20_0
sonoff_basic_0=basic_0
sonoff_basic_1=basic_1
sonoff_pow2_0=pow2_0
sonoff_pow_0=pow_0
sonoff_pow_1=pow_1
sonoff_pow_2=pow_2
sonoff_pow_3=pow_3
sonoff_pow_4=pow_4
sonoff_rfbridge_0=rfbridge_0

How about this solution
var SwitchRaw = Switch.substring(Switch.indexOf("_")+1, Switch.length))

2 Likes

That works, thanks very much @uk59821.

EDIT: there was an extra closing bracket had to delete first.