如何替换String类型的列中的子串?

wis*_*ame 2 java dataframe apache-spark apache-spark-sql

我正在尝试转换以下Scala行(从字符串中提取数字以及我在Scala shell中使用的数字):

val df2 = df.withColumn("only digits", regexp_replace(col("original"), "[^\\d]", ""))
Run Code Online (Sandbox Code Playgroud)

到它的Java等价物,我遇到了从org.apache.spark.sql.Column返回col("original")到所需的String类型的转换问题String.replaceAll().

我尝试了以下,但它没有编译(cast仍然返回一个Column).

import org.apache.spark.sql.Column;
import static org.apache.spark.sql.functions.*;
Dataset<Row> df2 = df.withColumn("new", col("original").cast("string").replaceAll("[^\\d]", ""));
Run Code Online (Sandbox Code Playgroud)

我还查看了列javadocs和上面导入的静态函数,但没有看到任何帮助.谢谢.

Jac*_*ski 5

我遇到了从org.apache.spark.sql.Column返回col("original")到所需String类型的转换问题String.replaceAll().

不会起作用.

您必须使用Column类型,因为它表示为该列中的每一行生成值的函数.这与Spark的类型系统一样多(或者Scala是精确的).

唯一的解决方案是使用函数对象(或编写用户定义的函数,即UDF).

使用regexp_replacetranslate作为您的用例.

regexp_replace(列e,字符串模式,字符串替换)将与regexp匹配的指定字符串值的所有子字符串替换为rep.

translate(Column src,String matchingString,String replaceString)使用replaceString中的字符翻译src中的任何字符.