2014-04-02 29 views
1

我需要发现一个字符串的第一个元素是否是char。 例子:如何判断Ruby字符串以什么开头?

string_1 = "Smith has 30 years" -----> TRUE (first element is a character) 
string_2 = "20/12/2013 Good Day" -----> FALSE (first element is not a character) 
string_3 = "<My name is John>" -----> FALSE (first element is not a character) 

使用“.initial”我能够获得每个字符串的第一个元素,但我不知道做测试

+5

字符串的任何元素为_character_,也许你说的是_letter_? – toro2k

回答

1

如果你的意思是,如果首先检查在串元素是信,你可以这样做:

string[0].match(/[a-zA-Z]/) 

,或者如奥雅纳Rakshit建议,您可以使用i选项在您的正则表达式忽略大小写:

string[0].match(/[a-z]/i) 

如果测试字符串以字母开头或者nil如果不是,则这些行将返回MatchData。如果你想truefalse值,你可以这样做:

!!string[0].match(/[a-z]/i) 
+0

使用'i'选项.... –

+0

'初始'方法是否可以在Ruby中使用字符串? –

+0

@AlokAnand我不知道这是什么'初始'方法,所以我把它从我的答案中删除。 –

1

您可以如下操作:

string[/\A[a-z]/i] 

看看这个 - str[regexp] → new_str or nil

在Ruby nilfalse对象视为具有虚假价值。

或如下使用Regexp#===

irb(main):001:0> /\A[a-z]/i === 'aaa' 
=> true 
irb(main):002:0> /\A[a-z]/i === '2aa' 
=> false 
+1

有一点'/^[a-z]/i ===“12345 \ nfoo”#=> true'。 – sawa

+0

@sawa非常感谢。..我想知道'^'和'\ A'之间的区别..现在明白了.. :-) –

+0

@ArupRakshit我想知道Ruby库有像Python的SciPy&NumPy 。我需要Ruby中的科学库来完成一个项目。 –

0

你可以这样做以下: -

regex = /[a-zA-Z]/ 

str[0][regex] 
#=> either a letter or nil 

str[0][regex].kind_of?(String) 
#=> true if first letter matches the regex or false if match return nil. 
1

此检测如果初始字符是英文字母(字母或下划线;不在于它是一个人物)。

string =~ /\A\w/ 
+0

有一点'\ w'包含'_'也...参见[here](http://www.ruby-doc.org/core-2.1.0/Regexp.html#class-Regexp-label-Character+类) –

0

只要尝试,

2.0.0-p247 :042 > /^[a-zA-Z]/ === 'Smith has 30 \n years' 
=> true 
OR 
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "Smith has \n 30 years" 
=> true 


2.0.0-p247 :042 > /^[a-zA-Z]/ === '20/12/2013 \n Good Day' 
=> false 
OR 
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "20/12/2013 \n Good Day" 
=> false 


2.0.0-p247 :042 > /^[a-zA-Z]/ === '<My name is \n John>' 
=> false 
OR 
2.0.0-p247 :042 > /\A[a-zA-Z]/ === "<My name \n is John>" 
=> false 
+0

我持有相同的答案... :-) –

+0

有小的差异。您可以使用^ OR \ A检查Ruby正则表达式中的起始字符 –

+0

正确是'\ A'。看看[这个评论](http://stackoverflow.com/questions/22807588/how-to-tell-what-ruby-string-starts-with/22807694?noredirect=1#comment34781715_22807694) –

相关问题