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

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 に答える
1

James Iry のエクストラクターの改良版:

object Int { 
  def unapply(s: String) = scala.util.Try(s.toInt).toOption 
} 
于 2016-08-06T09:12:59.667 に答える
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 に答える