gpt4 book ai didi

scala - 访问 Scala 解析器正则表达式匹配数据

转载 作者:行者123 更新时间:2023-12-01 22:00:28 25 4
gpt4 key购买 nike

我想知道是否可以从下面的语法中的匹配正则表达式生成MatchData。

object DateParser extends JavaTokenParsers {

....

val dateLiteral = """(\d{4}[-/])?(\d\d[-/])?(\d\d)""".r ^^ {
... get MatchData
}
}

当然,一个选择是在 block 内再次执行匹配,但由于 RegexParser 已经执行了匹配,我希望它将 MatchData 传递到 block 或存储它?

最佳答案

这是将您的 Regex 转换为 Parser 的隐式定义:

  /** A parser that matches a regex string */
implicit def regex(r: Regex): Parser[String] = new Parser[String] {
def apply(in: Input) = {
val source = in.source
val offset = in.offset
val start = handleWhiteSpace(source, offset)
(r findPrefixMatchOf (source.subSequence(start, source.length))) match {
case Some(matched) =>
Success(source.subSequence(start, start + matched.end).toString,
in.drop(start + matched.end - offset))
case None =>
Failure("string matching regex `"+r+"' expected but `"+in.first+"' found", in.drop(start - offset))
}
}
}

调整一下:

object X extends RegexParsers {
/** A parser that matches a regex string and returns the Match */
def regexMatch(r: Regex): Parser[Regex.Match] = new Parser[Regex.Match] {
def apply(in: Input) = {
val source = in.source
val offset = in.offset
val start = handleWhiteSpace(source, offset)
(r findPrefixMatchOf (source.subSequence(start, source.length))) match {
case Some(matched) =>
Success(matched,
in.drop(start + matched.end - offset))
case None =>
Failure("string matching regex `"+r+"' expected but `"+in.first+"' found", in.drop(start - offset))
}
}
}
val t = regexMatch("""(\d\d)/(\d\d)/(\d\d\d\d)""".r) ^^ { case m => (m.group(1), m.group(2), m.group(3)) }
}

示例:

scala> X.parseAll(X.t, "23/03/1971")
res8: X.ParseResult[(String, String, String)] = [1.11] parsed: (23,03,1971)

关于scala - 访问 Scala 解析器正则表达式匹配数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1815716/

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