如何有条件地从列中删除前两个字符

问题描述 投票:0回答:4

我有一些电话记录的以下数据,我想从每条记录中删除前两个值,因为它们是国家/地区代码。我可以使用 Scala、SparkHive 执行此操作的方式是什么?

phone
|917799423934|
|019331224595|
|  8981251522|
|917271767899|

我希望结果是:

phone
|7799423934|
|9331224595|
|8981251522|
|7271767899|

如何从每条记录或该列的每一行中删除前缀 91,01?

scala apache-spark hadoop apache-spark-sql hive
4个回答
5
投票

手机尺寸可以不同,可以使用这样的构造(Scala):

df.withColumn("phone", expr("substring(phone,3,length(phone)-2)"))

3
投票

我相信这是一个改进,更喜欢包含或等效的列表,但这里是:

import org.apache.spark.sql.functions._

case class Tel(telnum: String)
val ds = Seq(
     Tel("917799423934"),
     Tel("019331224595"),
     Tel("8981251522"),
     Tel("+4553")).toDS()

val ds2 = ds.withColumn("new_telnum", when(expr("substring(telnum,1,2)") === "91" || expr("substring(telnum,1,2)") === "01", expr("substring(telnum,3,length(telnum)-2)")).otherwise(col("telnum"))) 

ds2.show

返回:

+------------+----------+
|      telnum|new_telnum|
+------------+----------+
|917799423934|7799423934|
|019331224595|9331224595|
|  8981251522|8981251522|
|       +4553|     +4553|
+------------+----------+

我们可能需要考虑+,但没有任何说明。


3
投票

使用正则表达式

使用

regexp_replace
(如有必要,添加更多扩展代码):

select regexp_replace(trim(phone),'^(91|01)','') as phone --removes leading 91, 01 and all leading and trailing spaces
from table;

同样使用

regexp_extract

select regexp_extract(trim(phone),'^(91|01)?(\\d+)',2) as phone --removes leading and trailing spaces, extract numbers except first (91 or 01) 
from table;

1
投票

如果它们是字符串,那么对于 Hive 查询:

sql("select substring(phone,3) from table").show
© www.soinside.com 2019 - 2024. All rights reserved.