[SOLVED] Substring

Hi All,

I’m struggling to find any good documentation on Xtend if anyone can point me towards.

I want to a do a substring in a rule but I just can’t find the correct format.

This is so much easier in Python!

What I’m trying is.

	val String string1 = 'Hello'	
	val String string2 = string1.subString(0,1)	

However this isn’t correct.

Can someone point me to some docs so I can’t read those and refer to them when I need to know a command.

Or can someone rewrite Openhab in Python…

Simple correction. It is string1.substring(0,1) Notice the lower case S in substring. If you use the Designer interface you can get what is available by pressing ctrl-space. You would do this right after typing string1.

2 Likes

Perfect! Thanks

Is this working on rules?

I have this string, and I would like to use it.

{
  "ip": "aaaa",
  "hostname": "whatever.com",
  "city": "Antartida",
  "region": "Low",
  "country": "VB",
  "loc": "1.1234,1.12345",
  "postal": "12345",
  "org": "AFDSF"
}

I wonder how I could use substring, to get for example “loc” or “postal” ??

Thanks.

Isn;t that JSON?

I do not think so, the whole string is like this, and I would like to extract some words. :confused:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

100   228  100   228    0     0    678      0 --:--:-- --:--:-- --:--:--   680

{
  "ip": "aaaa",
  "hostname": "whatever.com",
  "city": "Antartida",
  "region": "Low",
  "country": "VB",
  "loc": "1.1234,1.12345",
  "postal": "12345",
  "org": "AFDSF"
}

Ah OK, some kind of scraping. We only know what you tell us.

I’d be looking for a way to extract the JSON from the whole string, i.e. get the string from { to }. I should think a regex would do that, but sorry I am not familiar.

And then use JsonPath. That way, you’d be fairly safe from the data source changing some other details.

There is a nifty string method called .substringBetween

rule "another rule"
when
    Item LivingRoom_WallSwitch changed
then
    var String myString = "blahblah{\"ip\": \"aaaa\",\"hostname\": \"whatever.com\",\"city\": \"Antartida\",\"region\": \"Low\",\"country\": \"VB\",\"loc\": \"1.1234,1.12345\",\"postal\": \"12345\",\"org\": \"AFDSF\"}"
    logInfo("TEST", myString)
    var String newString = myString.substringBetween("{","}") //Extract the JSON string between the curly brackets
    newString = "{" + newString + "}" // Add the JSON curly brackets back
    logInfo("TEST", newString)
    var String jsonString = transform("JSONPATH", "$.loc", newString) // Extract the loc value
    logInfo("TEST", jsonString) // Display : 1.1234,1.12345
    jsonString = transform("JSONPATH", "$.postal", newString) //Extract the postal value
    logInfo("TEST", jsonString) // Display: 12345
end
2 Likes