gpt4 book ai didi

Ruby:如果匹配则返回字符串的第一个字符,如果没有匹配则返回nil?

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:24 25 4
gpt4 key购买 nike

是否有内置的方法来获取字符串中字符的第一个匹配项或 nil。

我可以得到这样的第一个角色

'word'.match('o').to_s

但是如果没有匹配它给出 "" 而不是 nil

最佳答案

使用String#[match_str] :

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com