简体   繁体   English

Scala解析器组合器替换模式

[英]Scala Parser Combinator Replace Patterns

I got a below program, I can parse the pattern like convert(a.ACCOUNT_ID, string) to the expression, but I want to replace this pattern with CAST(a.ACCOUNT_ID AS VARCHAR) . 我有一个下面的程序,我可以将类似convert(a.ACCOUNT_ID, string)的模式解析为表达式,但是我想用CAST(a.ACCOUNT_ID AS VARCHAR)替换此模式。 I can do parse the result expression and replace the strings with the one above but there are expressions like this hence I don't want to do that way.. Is there any way that I can do a pattern replace? 我可以解析结果表达式,并用上面的表达式替换字符串,但是有这样的表达式,因此我不想这样做。.有什么方法可以进行模式替换吗? Like if I find a pattern as convert(a.ACCOUNT_ID, string) then replace it with CAST(a.ACCOUNT_ID AS VARCHAR) 就像如果我发现一个模式为convert(a.ACCOUNT_ID, string)然后将其替换为CAST(a.ACCOUNT_ID AS VARCHAR)

import scala.util.parsing.combinator._
import scala.util.parsing.combinator.lexical._
import scala.util.parsing.combinator.syntactical._
import scala.util.parsing.combinator.token._
import scala.util.parsing.input.CharSequenceReader


trait QParser  extends RegexParsers with JavaTokenParsers  {
  def knownFunction: Parser[Any] = ident ~ "(" ~ ident ~ ("." ~ ident <~ "," ~ ident ~ ")")

  def parse(inputString: String): Any = synchronized {
    phrase(knownFunction)(new CharSequenceReader(inputString)) match {
      case Success(result, _) => result
      case Failure(msg,_) => throw new DataTypeException(msg)
      case Error(msg,_) => throw new DataTypeException(msg)
    }
  }

 class DataTypeException(message: String) extends Exception(message)

}

object Parser extends QParser {
  def main(args: Array[String]) {
     println(parse("convert(a.ACCOUNT_ID, string)"));
  }
}

Output: (((convert~()~a)~(.~ACCOUNT_ID)) 输出: (((convert~()~a)~(.~ACCOUNT_ID))

I am not exactly sure what you mean with "there are expressions like this hence I don't want to do that way" , but you can transform the result of your parser function using the ^^ operator. 我不确定“有这样的表达式,所以我不想这样做”的意思 ,但是您可以使用^^运算符转换解析器函数的结果。

A transformation function for your parser could be : 您的解析器的转换函数可能是:

def knownFunction: Parser[String] = 
  ident ~ "(" ~ ident ~ "." ~ ident ~ "," ~ ident ~ ")" ^^ {
    case func ~ "(" ~ obj ~ "." ~ value ~ "," ~ castType ~ ")" =>
      val sqlFunc = Map("convert" -> "CAST")
      val sqlType = Map("string" -> "VARCHAR")
      s"${sqlFunc(func)}($obj.$value AS ${sqlType(castType)})"
  }

Using this updated function, the output of your application would be : 使用此更新的功能,您的应用程序的输出将是:

CAST(a.ACCOUNT_ID AS VARCHAR)

More information about the Scala Combinator Parsing can be found in a chapter of Programming in Scala, 1ed . 有关Scala组合器解析的更多信息,请参见《 Scala中编程》

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM