25

我正在寻找一种方法来匹配可能包含整数值的字符串。如果是,请解析它。我想编写类似于以下的代码:

  def getValue(s: String): Int = s match {
       case "inf" => Integer.MAX_VALUE 
       case Int(x) => x
       case _ => throw ...
  }

目标是如果字符串等于“inf”,则返回 Integer.MAX_VALUE。如果字符串是可解析的整数,则返回整数值。否则扔。

4

7 回答 7

42

定义提取器

object Int {
  def unapply(s : String) : Option[Int] = try {
    Some(s.toInt)
  } catch {
    case _ : java.lang.NumberFormatException => None
  }
}

您的示例方法

def getValue(s: String): Int = s match {
  case "inf" => Integer.MAX_VALUE 
  case Int(x) => x
  case _ => error("not a number")
}

并使用它

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...
于 2009-07-02T20:29:11.657 回答
11

我知道这是一个古老的已回答问题,但恕我直言,这是更好的:

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

当然,它不会抛出任何异常,但如果你真的想要它,你可以使用

getValue(someStr) getOrElse error("NaN")
于 2013-07-04T19:41:36.103 回答
8

您可以使用警卫:

def getValue(s: String): Int = s match {
  case "inf" => Integer.MAX_VALUE 
  case _ if s.matches("[+-]?\\d+")  => Integer.parseInt(s)
}
于 2011-06-19T10:55:36.340 回答
5

怎么样:

def readIntOpt(x: String) =
  if (x == "inf")
    Some(Integer.MAX_VALUE)
  else
    scala.util.Try(x.toInt).toOption
于 2014-10-10T00:23:06.440 回答
1

James Iry 提取器的改进版本:

object Int { 
  def unapply(s: String) = scala.util.Try(s.toInt).toOption 
} 
于 2016-08-06T09:12:59.667 回答
1

Scala 2.13推出以来String::toIntOption

"5".toIntOption   // Option[Int] = Some(5)
"abc".toIntOption // Option[Int] = None

我们可以在检查它是否等于“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
于 2019-01-18T15:34:00.917 回答
0
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
}
于 2009-07-02T18:50:25.100 回答