REGEX in rule to strip anything other then number

I have a JSONPATH that pulls out temp of my batteries, but the value includes a space and C so I can’t convert to F. So if the temp is 23 I get back “23 C” (minus the “”). I have that in a var, how do I strip out all but the number with REGEX in a rule?

My full var right now is:
var Number battery_temp = new Double(transform("JSONPATH", "$.devstatus.ports[?(@.Port==10)][0].Batt_temp", json))

Then:
postUpdate(Battery_Temp, (battery_temp * (9 div 5) + 32)

If you know that the string will always be numbers followed by a space and C, you can do a simple split to get at the number:

var String temp = transform(“JSONPATH”, “$.devstatus.ports[?(@.Port==10)][0].Batt_temp”, json).split(" ")[0]

You can do it with a regex too if you want but this is far easier.

2015-12-05 17:43:59.673 [ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule 'Outback JSON parsing': Could not invoke method: java.lang.String.split(java.lang.String,int) on instance: 23 C

rule:
var String battery_temp = transform("JSONPATH", "$.devstatus.ports[?(@.Port==10)][0].Batt_temp", json).split(" ")[0]

I assumed that transform returned a String. Wonder what itdoes return.

Try:

json).toString.split(" ")[0]

Ya, tried that, same error. Its odd because when I logInfo it I see “23 C”

To reference array values, you’d need to use:

    <array>.get(<index>)

instead of the more traditional Java array reference:

    <array>[<index>]

Using the above, this sample rule works (log output below):

import org.openhab.core.library.items.*

rule "test split rule"
when
  Time cron "0/5 * * * * ?"
then
  var String t = "10 C"
  var String[] u = t.split(" ")
  logInfo("test-split", "Before: " + t + " After: " + u.get(0))
end

Here’s the output:

16:30:05.003 DEBUG o.o.m.r.i.e.ExecuteRuleJob[:53]- Executing scheduled rule 'test split rule'
16:30:05.018 INFO  o.o.model.script.test-split[:53]- Before: 10 C After: 10
16:30:10.004 DEBUG o.o.m.r.i.e.ExecuteRuleJob[:53]- Executing scheduled rule 'test split rule'
16:30:10.018 INFO  o.o.model.script.test-split[:53]- Before: 10 C After: 10

Thanks Mark! That worked, but even tho I am saying var Number, it does not work like a number. As as an example if I add + 1 I get 231 rather then 24.

var String battery_temp_string = new String(transform("JSONPATH", "$.devstatus.ports[?(@.Port==10)][0].Batt_temp", json))
var Number battery_temp = battery_temp_string.split(" ").get(0)

Also tried “as Number”

You need to create a new Integer, Double, or big decimal out of what you get from the call to get(0).

var Number battery_temp = new Double(battry_temp_string.split(" ").get(0)

Otherwise it is just a String and “+” means concatination for Strings.