如何在Scala中从Regex创建解析器以解析路径? [英] How to create a parser from Regex in Scala to parse a path?

查看:158
本文介绍了如何在Scala中从Regex创建解析器以解析路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个解析器,试图在其中解析路径并进行算术计算.因为我不能将RegexParsers与StandardTokenParsers一起使用,所以我试图自己做.因此,我正在使用以下代码,这些代码是我从另一个讨论中摘录的一部分:

I am writing a parser in which I am trying to parse a path and do arithmetic calculations. since I cannot use RegexParsers with StandardTokenParsers I am trying to make my own. So I am using the following code for that which I picked a part of it from another discussion:

lexical.delimiters ++= List("+","-","*","/", "^","(",")",",")
import lexical.StringLit
def regexStringLit(r: Regex): Parser[String] =
acceptMatch( "string literal matching regex " + r,{ case  StringLit(s) if r.unapplySeq(s).isDefined => s })

def pathIdent: Parser[String] =regexStringLit ("/hdfs://([\\d.]+):(\\d+)/([\\w/]+/(\\w+\\.w+))".r)

def value :Parser[Expr] = numericLit ^^ { s => Number(s) }
def variable:Parser[Expr] =  pathIdent ^^ { s => Variable(s) }
def parens:Parser[Expr] = "(" ~> expr <~ ")"

def argument:Parser[Expr] = expr <~ (","?)
def func:Parser[Expr] = ( pathIdent ~ "(" ~ (argument+) ~ ")" ^^ { case f ~ _ ~ e ~ _ => Function(f, e) })
//some other code
 def parse(s:String) = {
    val tokens = new lexical.Scanner(s)
    phrase(expr)(tokens)
}

然后,我使用args(0)将输入发送到程序: "/hdfs://111.33.55.2:8888/folder1/p.a3d+1"

Then I use args(0) to send my input to the program which is : "/hdfs://111.33.55.2:8888/folder1/p.a3d+1"

这是我得到的错误:

[1.1] failure: string literal matching regex /hdfs://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)) expected

  /hdfs://111.33.55.2:8888/folder1/p.a3d
  ^

我尝试了简单路径,也注释了其余的代码,只是将路径部分留在那里,但似乎regexStringLit对我不起作用.我认为我在语法部分上是错误的.我不知道!

I tried simple path and also I commented the rest of the code and just left the path part there but it seems like the regexStringLit is not working for me. I think I am wrong in syntax part. I don't know!

推荐答案

我解决了该问题,即编写了特征并使用JavaTokenParsers而不是StandardToken Parser.

I solved it writing a trait and using JavaTokenParsers rather than StandardToken Parser.

 trait pathIdentifier extends RegexParsers{

      def pathIdent: Parser[String] ={
          """hdfs://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+))""".r
    }
}

@Tilo感谢您的帮助,您的解决方案也能正常运行,但是将扩展类更改为JavaTokenParser可以解决此问题.

@Tilo Thanks for your help your solution is working as well but changing extended class to JavaTokenParser helped to solve the problem.

这篇关于如何在Scala中从Regex创建解析器以解析路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆