I’m trying to figure out how to check if a string matches a regular expression, but I want to know if the entire string matches just once. Here’s my code but it seems absurdly long
def single_match(test_me, regex) ret_val = false test = regex.match(test_me) if (test.length==1 && test[0].length == test_me.length) ret_val = true end return ret_val end
is there an easier way to do this?
P.S. Here’s the method I’m really trying to write, since people always seem to ask why I want the gun these days:
def is_int(test_me) return single_match(test_me, /[0-9]*/) end
Edit Thanks everybody. Here’s where I’m really using it, but this regex stuff is always interesting to go through. Thanks for the great and educational answers.
You don’t need to do this, your method can be replaced by using the regular expression of
/^[0-9]*$/. The^tells it match start of a line and$tells it match end of the line. So it will match: start of line, 0 to any in range of 0 to 9, and finally end of line.And you don’t need the return statements, Ruby implicitly returns the last statement.
Edit:
It probably would be easier and look better to use the
to_iinstance method ofStringclass.Edit: (did some tests)
Comparing the performance between the two methods shows that
.to_i.to_s ==way is 5% faster. So it is up to personal preference to which ever looks better and if you want to handle leading zeroes.