是否有内置的方法来获取字符串中字符的第一个匹配项或 nil。
我可以得到这样的第一个角色
'word'.match('o').to_s
但是如果没有匹配它给出 ""
而不是 nil
最佳答案
If a
match_str
is given, that string is returned if it occurs in the string.Returns
nil
if (...) the match string cannot be found.
'word'['o'] #=> 'o'
'word'['q'] #=> nil
[]
方法非常通用,您还可以通过不同的方式传递正则表达式或索引。
关于Ruby:如果匹配则返回字符串的第一个字符,如果没有匹配则返回nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32141555/