在案例匹配中Scala Regex有什么问题?

时间:2021-10-29 03:25:58

I have two regexes doubleRegex and intRegex defined below:

我有两个正则表达式doubleRegex和intRegex定义如下:

scala> val doubleRegex = """^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$""".r
doubleRegex: scala.util.matching.Regex = ^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$

scala> val intRegex = """^[-+]?[0-9]*$""".r
intRegex: scala.util.matching.Regex = ^[-+]?[0-9]*$

Now I want to match a bunch of strings to detect their types:

现在我想匹配一堆字符串来检测它们的类型:

scala> List(".01", "11", "1.34").map{ s => 
       s match {
          case intRegex() => "INT"
          case doubleRegex() => "DOUBLE"
          case _ => "NONE"
       }
     }
res5: List[String] = List(NONE, INT, NONE)

Why does it not print List(DOUBLE, INT, DOUBLE) ?

为什么不打印List(DOUBLE,INT,DOUBLE)?

1 个解决方案

#1


2  

You have a capturing group specified in the doubleRegex, and when executing, you get the capturing groups extracted (and the first capturing group is empty with your examples).

您有一个在doubleRegex中指定的捕获组,并且在执行时,您将获取捕获组(并且第一个捕获组在您的示例中为空)。

Use doubleRegex(_*) to just check if a string matches without extracting capturing groups:

使用doubleRegex(_ *)只检查字符串是否匹配而不提取捕获组:

val doubleRegex = """^[-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?$""".r
val intRegex = """^[-+]?[0-9]*$""".r
print(List(".01", "11", "1.34").map{ s => 
   s match {
      case intRegex(_*) => "INT"
      case doubleRegex(_*) => "DOUBLE"
      case _ => "NONE"
   }
})

See IDEONE demo

请参阅IDEONE演示

Another solution is to change the capturing group into a non-capturing one:

另一种解决方案是将捕获组更改为非捕获组:

val doubleRegex = """^[-+]?[0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?$""".r
                                            ^^

Then, you can use your case intRegex() => "INT", and case doubleRegex() => "DOUBLE".

然后,你可以使用你的case intRegex()=>“INT”,case doubleRegex()=>“DOUBLE”。

See another IDEONE demo

查看另一个IDEONE演示

#1


2  

You have a capturing group specified in the doubleRegex, and when executing, you get the capturing groups extracted (and the first capturing group is empty with your examples).

您有一个在doubleRegex中指定的捕获组,并且在执行时,您将获取捕获组(并且第一个捕获组在您的示例中为空)。

Use doubleRegex(_*) to just check if a string matches without extracting capturing groups:

使用doubleRegex(_ *)只检查字符串是否匹配而不提取捕获组:

val doubleRegex = """^[-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?$""".r
val intRegex = """^[-+]?[0-9]*$""".r
print(List(".01", "11", "1.34").map{ s => 
   s match {
      case intRegex(_*) => "INT"
      case doubleRegex(_*) => "DOUBLE"
      case _ => "NONE"
   }
})

See IDEONE demo

请参阅IDEONE演示

Another solution is to change the capturing group into a non-capturing one:

另一种解决方案是将捕获组更改为非捕获组:

val doubleRegex = """^[-+]?[0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?$""".r
                                            ^^

Then, you can use your case intRegex() => "INT", and case doubleRegex() => "DOUBLE".

然后,你可以使用你的case intRegex()=>“INT”,case doubleRegex()=>“DOUBLE”。

See another IDEONE demo

查看另一个IDEONE演示