How do I test if a string holds an integer value?

This must be a common question, although I can’t find the answer and I can’t figure it out.

I’m looking for something like the following:

"15".isItAnInteger -> true
"-2".isItAnInteger -> true
"2.82938".isItAnInteger -> false
"hats".isItAnInteger -> false

One way would be to check with a regular expression (the following example also allows for an explicit + sign at the start of the integer).

(
var isInteger = { |str|
	var len = str.size;
	var result = str.findRegexpAt("[+-]?[0-9][0-9]*");
	if (result.isNil) {
		false;
	} { 
		len == result[1];	
	}
};

isInteger.("123.123").debug("test 1");
isInteger.("123").debug("test 2");
isInteger.("123a").debug("test 3");
isInteger.("whut").debug("test 4");
)

You can do .interpret in the string and if it is a valid SC expression you’ll get that back:

vat isItAnInt = “15”.interpret.isLindOf(Int)

I’m typing this on my phone so I’m not 100% sure the code above works, but something like that should.

/*
Josh Parmenter
www.realizedsound.net/josh
*/

Gah - isKindOf

/*
Josh Parmenter
www.realizedsound.net/josh
*/

Just one thought: calling interpret on a random string might be dangerous?

Not really any more dangerous than running your code in the interpreter in general. Why is the string random in this case?

“15”.interpret.isKindOf(Integer)

Also- there is an asInteger method on String. Not sure if that is safer or not but it is running it as a primitive so my gut says it probably is doing something safer.

I think running ‘interpret’ is generally safe UNLESS what is being interpreted includes .unixCmd and escaped strings:

""ls".unixCmd”.interpret

That shows that interpret CAN be used to interact with your system. But that also isn’t a very random string. So I guess it depends on how random your strings are.

Josh

Hi, the followings ar ok!

"15".interpret.isInteger // true
"-2".interpret.isInteger // true
"2.82938".interpret.isInteger // false

However, each of the followings firstly returns an error message and then returns false!

"hats".interpret.isInteger // false after ERROR: Variable 'hats' not defined.
"hats".interpret.isKindOf(Integer) // false after ERROR: Variable 'hats' not defined.
~isInteger = { |str| str.asInteger.asString == str }

~isInteger.("15") // true
~isInteger.("15 ") // false
~isInteger.("hats") // false
1 Like

I think it would be a good design to not crash the program because of such a small thing. That’s why some languages use Maybe values Just/Nothing. Just be careful that nothing inside .intepret will crash the program.

Just wrap it in a try block.

Whatever works.

Just be aware