tags:

views:

111

answers:

4

(Update: this question's main focus is to test the "nothing else" part)

Given a string s, which can contain anything, what is the most correct regexp in Ruby to check whether it is a single digit and nothing else? (a single digit and only a single digit).

A: 
^\d$

^ is start of the string, \d is a digit and $ is the end of the string

NOTE: as stated in comments ^ and $ work for both lines and strings so if you plan to have a multi-line input you should use \A and \Z

Jack
`^$` is for line, not string. `"asd\n7\n" =~ /^\d$/` => 4
Nakilon
He asked about a regexp, not about how to match it.. it is supposed that he knows how to enclose a regex inside `/../` and match with `=~` or `.match` :)
Jack
Actually `^` and `$` work for both start/end of line and of string..
Jack
+5  A: 

Use /\A\d\z/

irb(main):001:0> "asd\n7\n" =~ /\A\d\Z/
=> nil # works as false
irb(main):002:0> "asd\n7\n" =~ /\A\d\z/
=> nil # works as false
irb(main):083:0> "7\n"=~/\A\d\Z/
=> 0 # \Z fails, need \z
irb(main):084:0> "7\n"=~/\A\d\z/
=> nil # works as false
irb(main):005:0> "7" =~ /\A\d\Z/
=> 0 # works as true
irb(main):006:0> "7" =~ /\A\d\z/
=> 0 # works as true

http://www.zenspider.com/Languages/Ruby/QuickRef.html :

\z            end of a string
\Z            end of a string, or before newline at the end
Nakilon
what about `7\n`?
動靜能量
@Jian Lin, fixed.
Nakilon
it is a strange situation... you have the best solution so far, yet your vote is zero. I voted 1 for you but someone downvoted your answer.
動靜能量
@Jian Lin, shit happens )
Nakilon
+1 for link and correct solution. (If I could give +2, each would merit a +1 on its own. :-))
Donal Fellows
+1 for the most simple and effective answer
Simone Carletti
+1  A: 
s.scan(/\b\d\b/)

irb(main):001:0> "7\n" =~ /\b\d\z/
=> nil
irb(main):002:0> "7" =~ /\b\d\z/
=> 0
ghostdog74
I think this also gets `7\n`, which the OP pointed out in another comment as unacceptable.
eldarerathis
+1  A: 

Try /\A\d(?![\S\W])/?

irb(main):016:0> "7" =~ /\A\d(?![\S\W])/
=> 0
irb(main):017:0> "7\n" =~ /\A\d(?![\S\W])/
=> nil
irb(main):018:0> "aljda\n7\n" =~ /\A\d(?![\S\W])/
=> nil
irb(main):022:0> "85" =~ /\A\d(?![\S\W])/
=> nil
irb(main):023:0> "b5" =~ /\A\d(?![\S\W])/
=> nil
eldarerathis