Checking type of data returned by regexp

I have a regexp that detects a series of digits, or a series of characters including space.


I need to do one of two actions, depending on whether the result is a "number" or not. The $1 result is always a string though, even if it's just a string of digits.


$1.to_i returns 0 if $1 contains something other than digits, but it also returns 0 if the string is '0'.


Is there another way, other than converting it to an array and checking each character?
I don't know enough about Ruby and regexp, but can you filter for non-zero characters?


In that case, you only need to check the first non-zero character.


If it's not a digit, then you know why to_i returns zero


If it's a digit (non-zero due to the filter) and the to_i still returns zero, then there is another non-digit character inside.


No need to check every character of the string in that way.
I don't know if there are better ways to do this, but two ways I'd come up with:

The Kernel#Integer method can be used to create an integer based on a string. Unlike String#to_i this method will throw an ArgumentError you could catch when the String can not be converted as a whole.

You could also use another regular expression to check if the string conforms to numeric representation
(For example something like $1.strip.match(/^[+-]?\d+$/), however, this will also replace the "last match" data)
I've done this for now:


if $1.to_i.to_s == $1.to_s


# integer


else


# string


end


Seems to do the trick, and I could make it into a single line.


Still curious if there's something easier/better that doesn't rely on more regexp processing.
Named capture groups, maybe?

Code:
s = 'A'/\A(?<str>[A-Z ]+)|(?<int>\d+)\z/ =~ sif str  msgbox 'A-Z 'elsif int  msgbox '0-9'else  msgbox 'no match'end
yeah, thanks, but it's even longer than what I've got above, and still uses regexp again. I don't want to use a second regexp to interrogate the return value of the first regexp.


I think I'll just use this:

Code:
name = $1.to_i.to_s == $1.to_s ? $game_actors[$1.to_i].name : $1.to_s

Original thread: https://forums.rpgmakerweb.com/threads/checking-type-of-data-returned-by-regexp.35097/