Scala:如何将“MatchesRegex”细化与包含反引号的正则表达式(细化库)一起使用?

2024-05-06

The refined https://github.com/fthomas/refined库允许定义与给定匹配的细化regex,如图所示Readme:

import eu.timepit.refined._
import eu.timepit.refined.string._
import eu.timepit.refined.api.Refined

type MyType = String Refined MatchesRegex[W.`"[0-9]+"`.T]

虽然这工作得很好,但我们不能以这种方式定义与包含反引号的正则表达式匹配的类型,因为如所描述的here https://stackoverflow.com/a/55545195/5826349没有办法逃避 a 内的反引号literal:

 type MyType = String Refined MatchesRegex[W.`"(a|`)"`.T]

 // Getting a compile-error:
 // ']' expected but ')' found.

那么是否有一种方法来定义这样的类型(即MatchesRegex使用包含反引号的正则表达式)?


这样做的一种方法是使用单例类型 https://docs.scala-lang.org/sips/42.type.html在 Scala 2.13 中可用或类型级 Scala https://github.com/typelevel/scala/blob/typelevel-readme/notes/typelevel-4.md.

对于 Typelevel Scala,您需要在您的build.sbt:

scalaOrganization := "org.typelevel",
scalaVersion := "2.12.4-bin-typelevel-4", // Assuming you are using scala 2.12

并且您需要添加编译器标志-Yliteral-types:

scalacOptions := Seq(
                  ..., // Other options
                  "-Yliteral-types"
                 )

现在refined类型可以简单地是:

import eu.timepit.refined._
import eu.timepit.refined.api.Refined

type MyType = String Refined MatchesRegex["""(a|`)"""]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Scala:如何将“MatchesRegex”细化与包含反引号的正则表达式(细化库)一起使用? 的相关文章

随机推荐