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)
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)
| 归档时间: |
|
| 查看次数: |
14418 次 |
| 最近记录: |