gpt4 book ai didi

scala - 如何从字符串列中提取数字?

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

我的要求是从评论列中检索订单号,该评论列位于 comment 列中,并且始终以 R 开头。订单号应作为新列添加到表中。

输入数据:

code,id,mode,location,status,comment 
AS-SD,101,Airways,hyderabad,D,order got delayed R1657
FY-YT,102,Airways,Delhi,ND,R7856 package damaged
TY-OP,103,Airways,Pune,D,Order number R5463 not received

预期输出:

AS-SD,101,Airways,hyderabad,D,order got delayed R1657,R1657
FY-YT,102,Airways,Delhi,ND,R7856 package damaged,R7856
TY-OP,103,Airways,Pune,D,Order number R5463 not received,R5463

我在spark-sql中尝试过,我使用的查询如下:

val r = sqlContext.sql("select substring(comment, PatIndex('%[0-9]%',comment, length(comment))) as number from A")

但是,我收到以下错误:

org.apache.spark.sql.AnalysisException: undefined function PatIndex; line 0 pos 0

最佳答案

您可以使用具有定义的regexp_extract:

def regexp_extract(e: Column, exp: String, groupIdx: Int): Column

(R\\d{4}) 表示 R 后跟 4 位数字。您可以使用有效的正则表达式轻松适应任何其他情况

df.withColumn("orderId", regexp_extract($"comment", "(R\\d{4})" , 1 )).show

+-----+---+-------+---------+------+--------------------+-------+
| code| id| mode| location|status| comment|orderId|
+-----+---+-------+---------+------+--------------------+-------+
|AS-SD|101|Airways|hyderabad| D|order got delayed...| R1657|
|FY-YT|102|Airways| Delhi| ND|R7856 package dam...| R7856|
|TY-OP|103|Airways| Pune| D|Order number R546...| R5463|
+-----+---+-------+---------+------+--------------------+-------+

关于scala - 如何从字符串列中提取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47788528/

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