RegEx in Ruby: Just one match? -


I am trying to figure out whether a string matches a regular expression, but I want to know if the whole string matches only Here my code is but it looks a long time

  def single_match (test_me, regex) ret_val = false test = Regex.match (test_me) if (test.length == 1 & amp; test [0] .length == test_me.length) ret_val = true end return ret_val end  

An easy way to do this?

PS Here is the method that I am actually trying to write because people always ask why I want a gun these days:

  def is_int ( Test_me) return single_match (test_me, / [0- 9] * /) end  

edit Thanks everyone, but it always goes through regex content Interesting for Thanks for the great and educational answers.

You do not have to do this, your method may be / ^ [0- 9] * $ / replaced by using regular expression. ^ This corresponds to the beginning of a line and states that $ indicates at the end of the line match, then it will match: the beginning of the line, 0 9 in any range, and finally the end of the line.

Edit:

And you do not need a return statement, P>

It would be easy and it would be better to use the example example method.

  def is_int (test_me) test_me.to_i.to_s == test_me end  

edit: (some tests done)

The comparison between performance in two ways shows that .to_i.to_s == is 5% faster, so it is up to personal preference that looks better and If you want to handle the leading zero


Comments