Scala:匹配并解析一个整数字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1075676/
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
Scala: match and parse an integer string?
提问by Landon Kuhn
I'm looking for a way to matching a string that may contain an integer value. If so, parse it. I'd like to write code similar to the following:
我正在寻找一种匹配可能包含整数值的字符串的方法。如果是这样,解析它。我想编写类似于以下内容的代码:
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case Int(x) => x
case _ => throw ...
}
The goal is that if the string equals "inf", return Integer.MAX_VALUE. If the string is a parsable integer, return the integer value. Otherwise throw.
目标是如果字符串等于“inf”,则返回 Integer.MAX_VALUE。如果字符串是可解析的整数,则返回整数值。否则扔。
回答by James Iry
Define an extractor
定义提取器
object Int {
def unapply(s : String) : Option[Int] = try {
Some(s.toInt)
} catch {
case _ : java.lang.NumberFormatException => None
}
}
Your example method
您的示例方法
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case Int(x) => x
case _ => error("not a number")
}
And using it
并使用它
scala> getValue("4")
res5: Int = 4
scala> getValue("inf")
res6: Int = 2147483647
scala> getValue("helloworld")
java.lang.RuntimeException: not a number
at scala.Predef$.error(Predef.scala:76)
at .getValue(<console>:8)
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:4)
at RequestResult$.<clinit>(<console>)
at RequestResult$result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Na...
回答by rsenna
I know this is an old, answered question, but this is better IMHO:
我知道这是一个旧的,已回答的问题,但恕我直言,这更好:
scala> :paste
// Entering paste mode (ctrl-D to finish)
val IntRegEx = "(\d+)".r
def getValue(s: String): Option[Int] = s match {
case "inf" => Some(Integer.MAX_VALUE)
case IntRegEx(num) => Some(num.toInt)
case _ => None
}
// Exiting paste mode, now interpreting.
IntRegEx: scala.util.matching.Regex = (\d+)
getValue: (s: String)Option[Int]
scala> getValue("inf")
res21: Option[Int] = Some(2147483647)
scala> getValue("123412")
res22: Option[Int] = Some(123412)
scala> getValue("not-a-number")
res23: Option[Int] = None
Of course, it doesn't throw any exceptions, but if you really want it, you may use
当然,它不会抛出任何异常,但如果你真的想要它,你可以使用
getValue(someStr) getOrElse error("NaN")
回答by cayhorstmann
You could use a guard:
你可以使用警卫:
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case _ if s.matches("[+-]?\d+") => Integer.parseInt(s)
}
回答by Erik Kaplun
How about:
怎么样:
def readIntOpt(x: String) =
if (x == "inf")
Some(Integer.MAX_VALUE)
else
scala.util.Try(x.toInt).toOption
回答by David Portabella
an improved version of James Iry's extractor:
James Iry 提取器的改进版本:
object Int {
def unapply(s: String) = scala.util.Try(s.toInt).toOption
}
回答by Xavier Guihot
Since Scala 2.13introduced String::toIntOption:
自Scala 2.13推出以来String::toIntOption:
"5".toIntOption // Option[Int] = Some(5)
"abc".toIntOption // Option[Int] = None
we can cast the Stringas an Option[Int]after checking if it's equal to "inf":
我们可以在检查它是否等于“inf”之后将其转换String为Option[Int]:
if (str == "inf") Some(Int.MaxValue) else str.toIntOption
// "inf" => Option[Int] = Some(2147483647)
// "347" => Option[Int] = Some(347)
// "ac4" => Option[Int] = None
回答by agilefall
def getValue(s: String): Int = s match {
case "inf" => Integer.MAX_VALUE
case _ => s.toInt
}
println(getValue("3"))
println(getValue("inf"))
try {
println(getValue("x"))
}
catch {
case e => println("got exception", e)
// throws a java.lang.NumberFormatException which seems appropriate
}

