Scala:如何将`MatchesRegex` 细化与包含反引号(细化库)的正则表达式一起使用? [英] Scala: How to use a `MatchesRegex` refinement with a regex containing a backtick (refined library)?
问题描述
refined 库允许定义与给定 regex
匹配的细化,如Readme
所示:
The refined library allows to define refinement that matches a given regex
, as shown in the 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]
虽然这工作得很好,但我们不能以这种方式定义与包含反引号的正则表达式匹配的类型,因为如此处所述 没有办法在 literal
中转义反引号:
While this works perfectly fine, we can't define this way a type that matches a regex containing a backtick, because as describe here there is no way to escape a backtick within a literal
:
type MyType = String Refined MatchesRegex[W.`"(a|`)"`.T]
// Getting a compile-error:
// ']' expected but ')' found.
那么有没有办法定义这样的类型(即 MatchesRegex
与包含反引号的正则表达式)?
So would there be a way to define such a type (i.e MatchesRegex
with a regex containing a backtick)?
推荐答案
这样做的方法是使用 单例类型 在 Scala 2.13 或 Typelevel Scala.
A way to do so is to use singleton types available in Scala 2.13 or Typelevel Scala.
对于 Typelevel Scala,您需要在 build.sbt
中添加/替换:
For Typelevel Scala, you need to add / replace in your build.sbt
:
scalaOrganization := "org.typelevel",
scalaVersion := "2.12.4-bin-typelevel-4", // Assuming you are using scala 2.12
并且你需要添加编译器标志-Yliteral-types
:
And you need to add the compiler flag -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|`)"""]
这篇关于Scala:如何将`MatchesRegex` 细化与包含反引号(细化库)的正则表达式一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!