parsing - 如何编写统一 diff 语法的解析器

标签 parsing scala parser-combinators

我应该使用 RegexParsers、StandardTokenParsers 还是这些都适合解析这种语法?语法示例可以在 here 中找到。 .

最佳答案

我会使用正则表达式。它简化了一些事情,并使其余的事情标准化。

def process(src: scala.io.Source) {
  import scala.util.matching.Regex

  val FilePattern = """(.*) ''(.*)''"""
  val OriginalFile = new Regex("--- "+FilePattern, "path", "timestamp")
  val NewFile = new Regex("+++ "+FilePattern, "path", "timestamp")
  val Chunk = new Regex("""@@ -(\d+),(\d+) +(\d+),(\d+) @@""", "orgStarting", "orgSize", "newStarting", "newSize")
  val AddedLine = """+(.*)""".r
  val RemovedLine = """-(.*)""".r
  val UnchangedLine = """ (.*)""".r

  src.getLines() foreach {
    case OriginalFile(path, timestamp) => println("Original file: "+path)
    case NewFile(path, timestamp) => println("New file: "+path)
    case Chunk(l1, s1, l2, s2) => println("Modifying %d lines at line %d, to %d lines at %d" format (s1, l1, s2, l2))
    case AddedLine(line) => println("Adding line "+line)
    case RemovedLine(line) => println("Removing line "+line)
    case UnchangedLine(line) => println("Keeping line "+line)
  }
}

关于parsing - 如何编写统一 diff 语法的解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3560073/

相关文章:

Java字符串识别

python - 从/proc/net/tcp6 解析 IPv6 地址(python 2.7)

scala - 如何检查 Failure[T] 中包含哪个异常?

eclipse - 如何在 Eclipse 中使 Scala 隐式显式化

parsing - 避免在解析器库中使用解析器失败

scala 组合器解析器保留原始输入

scala - 使用 Scala 组合器解析器区分整数和 float

C#疑惑,找数据类型

C#计算解析器

json - 在 Spray 1.2.0 路由中将查询字符串参数与 JSON 实体相结合