regex
函數提取
import scala.util.matching.Regex// 輸入表達式
val expression = "[a#0, round(a#0, 0) AS round(a, 0)#1, abs(a#0) AS abs(a)#2, len(cast(a#0 as string)) AS len(a)#3]"// 定義一個正則表達式來提取函數名稱
val functionPattern: Regex = """(\w+)\((.*?)\)""".r// 提取所有函數的名稱并去重
val functions = functionPattern.findAllIn(expression).matchData.map(m => m.group(1)) // 只提取函數名.toList // 轉換為List.distinct // 去重// 打印結果
println(functions)
object ExtractFunctionNames {def main(args: Array[String]): Unit = {val input = "[round(a#0, 2) AS round(a, 2)#1, a#0]"// 使用正則表達式匹配所有類似于函數名的部分val regex = """([a-zA-Z_][a-zA-Z0-9_]*)\(""".r// 提取所有函數名并去重val functionNames = regex.findAllIn(input).matchData.map(_.group(1)) // 獲取匹配的函數名.toSet // 使用 Set 去重// 輸出去重后的函數名println(functionNames)}
}
提取 Aggregate 函數
import scala.util.matching.Regexval expr = "HashAggregate(keys=[ss_store_sk#9], functions=[sum(UnscaledValue(ss_sales_price#15)), sum(UnscaledValue(ss_net_profit#24))])"// 定義正則表達式來匹配functions=后的函數列表
val pattern: Regex = """functions=\[(.*?)\]""".r// 從字符串中查找匹配到的函數列表
val functionList = pattern.findAllMatchIn(expr).flatMap { m =>// 通過逗號分隔函數名,然后提取每個函數名val functions = m.group(1).split(",").map(_.trim) // 按逗號分隔并去除多余空格functions.map { f =>// 提取函數名(去掉函數名后的括號)f.split("\\(")(0)}
}.toList.distinctprintln(functionList)
提取 Window 函數
import scala.util.matching.Regex// 輸入字符串
val input = "[ss_store_sk#9, ss_customer_sk#5], [ss_sold_date_sk#2 DESC NULLS LAST], row_number(), 1, Final"// 使用正則表達式:匹配函數名(以括號 `()` 結尾的部分)
val pattern: Regex = """(\w+)(?=\()""".r// 使用正則表達式提取函數名
val functionNames = pattern.findAllIn(input).toSet// 輸出結果
println(functionNames) // List(row_number)