2010-01-25 17 views

回答

34

如果您在正则表达式意义上表示空白字符,制表符,换行符,回车符或(我认为)换页符的意思,则任何提供的答案都可以使用:

s.match(/\s/) 
s.index(/\s/) 
s =~ /\s/ 

甚至(以前没有提到)

s[/\s/] 

如果你只在检查空格字符兴趣的话,那么试试你的

s.match(" ") 
s.index(" ") 
s =~// 
s[" "] 
偏好

从IRB(红宝石1.8.6):

s = "a b" 
puts s.match(/\s/) ? "yes" : "no" #-> yes 
puts s.index(/\s/) ? "yes" : "no" #-> yes 
puts s =~ /\s/ ? "yes" : "no" #-> yes 
puts s[/\s/] ? "yes" : "no" #-> yes 

s = "abc" 
puts s.match(/\s/) ? "yes" : "no" #-> no 
puts s.index(/\s/) ? "yes" : "no" #-> no 
puts s =~ /\s/ ? "yes" : "no" #-> no 
puts s[/\s/] ? "yes" : "no" #-> no 
+1

使用最新的[String#match?](http://ruby-doc.org/core-2.4.1/String.html#method-i-match-3F)在Ruby v2中首次亮相.4,所以现在可以写's.match?(/ \ s /)'。 – 2017-07-04 17:57:29

2

可以使用索引

"mystring".index(/\s/) 
+0

是不是一个制表符空白? – Eli 2010-01-25 06:51:58

4

它通常是做过这样的:

str =~ /\s/ 

你可以阅读有关正则表达式here

0

我真的很喜欢使用count这一点。

"hello 1".count("") #=> 0 
"hello 1".count(" ") #=> 1 
" hello 1".count(" ") #=> 2 


"hello 1".count(" ") > 0 #=> true