spark DataFrame正則表達式
注意 在spark中使用正則的時候,需要時時刻刻加上轉義自符
'\'需要使用'\\',例如'\w'需要使用'\\w'
正則表達式,使用的庫在sql.funtions 下,如導入split和regexp_extract
import org.apache.spark.sql.functions.{regexp_extract,split}
1.1 split
split 切分字符串
可通過下面的,形如udf函數實現
val splitFunc=udf((arg:String)=>{arg.split(',|[| ')[0]})
也可使用
var data1 = data.withColumn(colName, split(col(colName), pattern=',|[| ')(0))
1.2 regexp_extract
regexp_extract(string subject, string pattern, int index) 將字符串subject按照pattern正則表達式的規則拆分,返回index指定的字符
例子:匹配至少有兩個非數字的gid
val data =fake_data.select(regexp_extract(fake_data("gid"),"^\\d{2}",0).alias("gid"))
1.3 like & rlike的區別
1.3.1 like:
%:匹配零個及多個任意字符
_:與任意單字符匹配
[]:匹配一個範圍
[^]:排除一個範圍
ESCAPE 關鍵字定義轉義符 WHERE ColumnA LIKE ‘%5/%%’ ESCAPE ‘/’
like不是正則,而是通配符
1.3.2 rlike
rlike是正則,正則的寫法與java一樣。’‘需要使用’\’,例如’\w’需要使用’\w’
A rlike ‘\d+’ 匹配一個或多個數字, not A rlike ‘\d+’ 匹配非數字
** 參考鏈接**
正則表達式參考鏈接:https://www.cnblogs.com/wxshi/p/6827056.html