How to check if part of a string contains only numbers

So i’m trying to create a rule that checks if value contains a delimiter and if it does, split value at that delimiter and send it as command. However i need to check it this value contains numbers only, because otherwise bad thing happen :wink:

	when
		Item MultiSwitch_PROXY received command
	then
		if (MultiSwitch_PROXY.state.toString.contains(" ")) { //check to see if it contains a delimiter
			var MultiSwitch_PROXYBuffer = MultiSwitch_PROXY.state.toString.split(" ") //split
			if (MultiSwitch_PROXYBuffer.get(0) == "Speakers" && MultiSwitch_PROXYBuffer.get(1) instanceof DecimalType) { //to check if volume is a number - but this is never true 
				logInfo("TEST-BEFORE"," volume set to "+ MultiSwitch_PROXYBuffer.get(1))
			}
		}
end

so what i need is a way to determine if MultiSwitch_PROXYBuffer.get(1) is a number and then do something with it.

You could try this. If it throws an exception, it’s not a number.

    try {
        val int num = Integer.parseInt(MultiSwitch_PROXYBuffer.get(1))
    } catch (Exception e) {
        // String is not a number
    }

Note that you need to include this import at the beginning of the rule.

import java.lang.Integer

I suppose it would be more correct to do this:

import java.lang.Integer
import java.lang.NumberFormatException

Then in the rule

    try {
        val int num = Integer.parseInt(MultiSwitch_PROXYBuffer.get(1))
    } catch (NumberFormatException e) {
        // String is not a number
    }
1 Like

Thanks!