如何在 Scala 中验证数字字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31983084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:27:13  来源:igfitidea点击:

How do I validate a Numeric character in scala?

scala

提问by yash

my application takes in a string like this (-110,23,-111.9543633) I need to validate/retrieve inside scala script that the string whether it is Numeric or not?

我的应用程序接受这样的字符串 (-110,23,-111.9543633) 我需要在 Scala 脚本中验证/检索该字符串是否为数字?

采纳答案by yash

I tried this and its working fine:

我试过这个并且它工作正常:

val s = "-1112.12" s.isNumeric && (s.contains('.')==false)

val s = "-1112.12" s.isNumeric && (s.contains('.')==false)

回答by elm

Consider scala.util.Tryfor catching possible exceptions in converting a string onto a numerical value, as follows,

考虑scala.util.Try在将字符串转换为数值时捕获可能的异常,如下所示,

Try("123".toDouble).isSuccess
Boolean = true

Try("a123".toDouble).isSuccess
Boolean = false

As of ease of use, consider this implicit,

至于易用性,请考虑这个隐含的,

implicit class OpsNum(val str: String) extends AnyVal {
  def isNumeric() = scala.util.Try(str.toDouble).isSuccess
}

Hence

因此

"-123.7".isNumeric
Boolean = true

"-123e7".isNumeric
Boolean = true

"--123e7".isNumeric
Boolean = false

回答by Sascha Kolberg

Assuming you want not only to convert by using Try(x.toInt)or Try(x.toFloat)but actually want a validatorthat takes a Stringand return trueiff the passed Stringcan be converted to a Awith implicit evidence: Numeric[A].

假设您不仅想要通过 using 进行转换,Try(x.toInt)或者Try(x.toFloat)实际上想要一个接受 a并返回的验证器,如果传递的可以转换为with 。StringtrueStringAimplicit evidence: Numeric[A]

Then I would say: Afaik, noit is not possible. Especially, since Numericis not sealed. That is you can create your own implementations of Numeric

然后我会说:Afaik,不,这是不可能的。尤其是,因为Numeric不是密封的。也就是说,您可以创建自己的实现Numeric

Primitive types like Int, Long, Float, Doublecan be easily extracted with a regular expression.

Int, Long, Float, Double可以使用正则表达式轻松提取诸如此类的原始类型。