如何提取 PySpark 数据框中正则表达式模式的所有实例?

ARC*_*row 3 python regex apache-spark pyspark

StringType()在 PySpark 数据框中有一列。我想从该字符串中提取正则表达式模式的所有实例,并将它们放入新的列中ArrayType(StringType())

假设正则表达式模式是[a-z]\*([0-9]\*)

Input df:
+-----------+
|stringValue|
+-----------+
|a1234bc123 |
|av1tb12h18 |
|abcd       | 
+-----------+

Output df:
+-----------+-------------------+
|stringValue|output             |
+-----------+-------------------+
|a1234bc123 |['1234', '123']    |
|av1tb12h18 |['1', '12', '18']  |
|abcd       |[]                 |
+-----------+-------------------+
Run Code Online (Sandbox Code Playgroud)

Zyg*_*ygD 9

Spark 3.1+regexp_extract_all可用。

regexp_extract_all(str, regexp[, idx])- 提取与表达式str匹配regexp并对应于正则表达式组索引的所有字符串。

df = df.withColumn('output', F.expr(r"regexp_extract_all(stringValue, '[a-z]*(\\d+)', 1)"))

df.show()
#+-----------+-----------+
#|stringValue|     output|
#+-----------+-----------+
#| a1234bc123|[1234, 123]|
#| av1tb12h18|[1, 12, 18]|
#|       abcd|         []|
#+-----------+-----------+
Run Code Online (Sandbox Code Playgroud)