Scala:匹配并解析整数字符串?

Lan*_*uhn 24 parsing scala match

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

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

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

Jam*_*Iry 41

定义一个提取器

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

你的示例方法

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

并使用它

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...
Run Code Online (Sandbox Code Playgroud)

  • 实际上,使用正则表达式来匹配字符串的内容可能更有效,而不是捕获异常. (4认同)

rse*_*nna 10

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

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
Run Code Online (Sandbox Code Playgroud)

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

getValue(someStr) getOrElse error("NaN")
Run Code Online (Sandbox Code Playgroud)


cay*_*ann 8

你可以使用一个警卫:

def getValue(s: String): Int = s match {
  case "inf" => Integer.MAX_VALUE 
  case _ if s.matches("[+-]?\\d+")  => Integer.parseInt(s)
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*lun 5

怎么样:

def readIntOpt(x: String) =
  if (x == "inf")
    Some(Integer.MAX_VALUE)
  else
    scala.util.Try(x.toInt).toOption
Run Code Online (Sandbox Code Playgroud)