gpt4 book ai didi

regex - 避免在 ScalaTest 中针对正则表达式的 matchPattern 上的弃用警告

转载 作者:行者123 更新时间:2023-12-01 03:23:13 27 4
gpt4 key购买 nike

考虑以下用于测试 IdentifierRe 的代码和 IntPart :

// Code under test
val IdentifierRe = "([a-z]+)([0-9]+)".r
object IntPart {
def unapply(arg: String): Option[Int] = Some(arg.toInt)
}

// Test cases
"foo123" should matchPattern { case IdentifierRe("foo", IntPart(123)) => }
"foo 123" should not fullyMatch IdentifierRe

它编译但给出以下警告:

warning: method unapplySeq in class Regex is deprecated (since 2.11.0): extracting a match result from anything but a CharSequence or Match is deprecated



我相信问题在于 matchPattern接受 PartialFunction[Any, _] ,导致弃用 Regex#unapplySeq(Any)用于提取。我可以解决它:
"foo123" match {
case IdentifierRe("foo", IntPart(123)) => succeed
case _ => fail
}

甚至:
"foo123" should fullyMatch regex (IdentifierRe withGroups("foo", "123"))

但是在仍然使用 IntPart 的同时,是否有更简洁的方法来避免警告?测试用例中的提取器?这个想法是 IdentifierReIntPart经常一起用于模式匹配,我们想在测试用例中模仿它。

最佳答案

考虑定义 custom matcher像这样

def matchRegexPattern(right: PartialFunction[String, _]): Matcher[String] =
(left: String) =>
MatchResult(
right.isDefinedAt(left),
s"$left does not match regex pattern",
s"$left does match regex pattern "
)

请注意我们如何替换 AnyStringPartialFunction[String, _]应该注意警告。现在像这样模式匹配
"foo123" should matchRegexPattern { case IdentifierRe("foo", IntPart(123)) => }

关于regex - 避免在 ScalaTest 中针对正则表达式的 matchPattern 上的弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com