繁体   English   中英

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

[英]Scala: How to use a `MatchesRegex` refinement with a regex containing a backtick (refined library)?

精炼库允许定义与给定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]

虽然这工作完全正常,我们不能定义这样一个含有反引号正则表达式相匹配的类型,因为形容这里是没有办法逃避内的反引号literal

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

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

那么有没有办法定义这样的类型(即MatchesRegex与包含反引号的正则表达式)?

一种方法是使用 Scala 2.13 或Typelevel Scala 中可用的单例类型

对于 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|`)"""]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM