如何在scala中的数据帧上应用正则表达式模式?

如何在scala中的数据帧上应用正则表达式模式?,scala,apache-spark,Scala,Apache Spark,我有一个dataframe:yearDF,我通过阅读RDBMS表得到,如下所示: val yearDF = spark.read.format("jdbc").option("url", connectionUrl) .option("dbtable", s"(${query}) as year2017")

我有一个dataframe:yearDF,我通过阅读RDBMS表得到,如下所示:

val yearDF = spark.read.format("jdbc").option("url", connectionUrl)
                                                   .option("dbtable", s"(${query}) as year2017")
                                                   .option("user", devUserName)
                                                   .option("password", devPassword)
                                                   .option("numPartitions",15)
                                                   .load()
在我们的项目中,我的架构师说,在从RDBMS表读取的任何数据被持久化/加载到HDFS上的配置单元表之前,我们需要对其应用正则表达式模式。这是我必须使用的正则表达式模式:

"regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(%s, E'[\\\\n]+', ' ', 'g' ), E'[\\\\r]+', ' ', 'g' ), E'[\\\\t]+', ' ', 'g' ), E'[\\\\cA]+', ' ', 'g' ), E'[\\\\ca]+', ' ', 'g' ) as %s"

有人能告诉我如何在数据框中的所有列上应用上述正则表达式模式:
yearDF
以形成新的数据框吗?

yearDF。columns
将返回一个
数组[String]
,其中包含
yearDF

映射
以获取字符串表达式。使用字符串函数
.format
将说明符
%s
替换为列名

val regexExpr = yearDF.columns.map(c => "regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(%s, E'[\\\\n]+', ' ', 'g' ), E'[\\\\r]+', ' ', 'g' ), E'[\\\\t]+', ' ', 'g' ), E'[\\\\cA]+', ' ', 'g' ), E'[\\\\ca]+', ' ', 'g' ) as %s".format(c ,c))
将生成的表达式传递给
selectExpr

yearDF.selectExpr(regexExpr : _*)

在这种情况下,$c和%s有多大区别?没有太大区别。我以为您是手动创建表达式的。如果要使用
%s
,则需要使用
.format
。我编辑了答案来反映这一点。啊,好的。我不是手动创建它。这已经在其他代码中使用,并且被告知将其用于数据摄取。我现在就试试,然后回来。很抱歉反应太晚。将其更改为%s后,获取以下异常:线程“main”org.apache.spark.sql.catalyst.parser.ParseException中的异常:当前不支持类型为“E”的文本。(第1行,位置88)regexp_替换(regexp_替换)(regexp_替换)(regexp_替换)(regexp_替换(regexp_替换)(预测_id,E'[\\n]+',''g'),E'[\\r]+','g'),E[\\t]+在com.partition.source.YearPartition$.main(YearPartition.scala:93)的com.partition.source.YearPartition.main(YearPartition.scala:93)中,将“,”,“,”,“,”,“,”,g'),E'[\\cA]+',“,”,E'[\\cA]+',“g'),作为预测,这看起来与正则表达式有关。列名
forecast\u id
似乎已替换为fine。