如何为路径编写Scala解析器?

时间:2015-06-12 22:30:52

标签: scala parsing path

我是scala的初学者,编写一个scala解析器,我需要解析这样的路径(假设x是一个整数): /hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg

我尝试了以下不确定我是否走在正确的轨道上:

  def pathIdent: Parser[String] = ("/hdfs""+"""(\d+~\.\d*)"""+ ~("""(u[a-zA-Z0-9])*+"""+"\.[\\'"jpg]"").r

我知道它有错误!我真的需要帮助!

1 个答案:

答案 0 :(得分:3)

你的正则表达式看起来有错字。试试这样的事情:

scala> val regex = """^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)""".r
regex: scala.util.matching.Regex = ^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)

一些示例路径:

scala> val path = """/hfds://111.222.33.444:5555/path1/path2/filename1.jpg"""
path: String = /hfds://111.222.33.444:5555/path1/path2/filename1.jpg

然后进行匹配:

scala> val regex(numbers,afterColon,fullPath,filename) = path
numbers: String = 111.222.33.444
afterColon: String = 5555
fullPath: String = path1/path2/filename1.jpg
filename: String = filename1.jpg

要捕获解析错误,您可以使用这样的模式匹配,例如:解析文件名:

def parseFilename(path: String): Option[String] = path match {
     case regex(numbers,afterColon,fullPath,filename) => Some(filename)
     case _ => println("parse error");None
}

它将返回该文件名的选项:

scala> parseFilename(path)
res0: Option[String] = Some(filename1.jpg)

scala> val badPath="""/hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg"""
badPath: String = /hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg

scala> parseFilename(badPath)
parse error
res1: Option[String] = None