gpt4 book ai didi

java - 如何替换字符串类型列中的子字符串?

转载 作者:行者123 更新时间:2023-12-02 16:16:13 25 4
gpt4 key购买 nike

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

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

到其 Java 等效项,我在从 col("original") 返回的 org.apache.spark.sql.Column 转换为 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]", ""));

我还查看了专栏javadocs在上面导入的静态函数中,但没有看到任何帮助。谢谢。

最佳答案

I am having problems with the conversion from org.apache.spark.sql.Column returned by col("original") to the String type required by String.replaceAll().

不会工作。

您必须使用Column类型,因为它代表一个为该列中的每一行生成值的函数。 Spark 类型系统与 Java(或者准确地说是 Scala)的类型系统一样。

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

使用regexp_replacetranslate适合您的用例。

regexp_replace(Column e, String pattern, String replacement) Replace all substrings of the specified string value that match regexp with rep.

translate(Column src, String matchingString, String replaceString) Translate any character in the src by a character in replaceString.

关于java - 如何替换字符串类型列中的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com