【问题标题】:Check if string starts with number检查字符串是否以数字开头
【发布时间】:2023-01-01 03:25:37
【问题描述】:

如何检查我的字符串是否以数字开头?

我试图通过使用 starts_with ruby​​ 方法来完成这项工作,但没有成功:

<% if line.start_with?("ANY NUMBER") %>

谢谢!

【问题讨论】:

  • 尝试使用正则表达式:line.start_with?(/[0-9]/)
  • “不走运”的错误描述不够准确,我们无法帮助您。什么不起作用?如何它不起作用吗?你的代码有什么问题?你收到错误信息了吗?错误信息是什么?您得到的结果不是您期望的结果吗?您期望什么结果,为什么,您得到的结果是什么,两者有何不同?您观察到的行为不是您想要的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有什么不同?

标签: ruby


【解决方案1】:

只需这样做:

def starts_with_number?(str)
  str.start_with?(*'0'..'9')
end

puts starts_with_number?("123abc") # true

puts starts_with_number?("abc123") # false

puts starts_with_number?("1.23") # true

puts starts_with_number?("-123") # true

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2019-08-24
    • 2015-04-15
    相关资源
    最近更新 更多