In Ruby, what is the most correct way to use Regular Expression to match a single digit and **nothing else**?
(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 corr开发者_如何学JAVAect regexp in Ruby to check whether it is a single digit and nothing else? (a single digit and only a single digit).
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
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
s.scan(/\b\d\b/)
irb(main):001:0> "7\n" =~ /\b\d\z/
=> nil
irb(main):002:0> "7" =~ /\b\d\z/
=> 0
^\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
精彩评论