首页 > 解决方案 > 我对具有多个匹配项的正则表达式提取有疑问

问题描述

我正在尝试从字符串 "60 ML of paracetomol and 0.5 ML of XYZ" 中提取 60 ML 和 0.5 ML。此字符串是 spark 数据框中 X 列的一部分。虽然我能够测试我的正则表达式代码以在正则表达式验证器中提取 60 ML 和 0.5 ML,但我无法使用 regexp_extract 提取它,因为它仅针对第一个匹配项。因此我只得到 60 毫升。

你能建议我使用 UDF 的最佳方法吗?

标签: pyspark

解决方案


以下是使用 python UDF 的方法:

from pyspark.sql.types import *
from pyspark.sql.functions import *
import re

data = [('60 ML of paracetomol and 0.5 ML of XYZ',)]
df = sc.parallelize(data).toDF('str:string')

# Define the function you want to return
def extract(s)
    all_matches = re.findall(r'\d+(?:.\d+)? ML', s)
    return all_matches

# Create the UDF, note that you need to declare the return schema matching the returned type
extract_udf = udf(extract, ArrayType(StringType()))

# Apply it
df2 = df.withColumn('extracted', extract_udf('str'))

Python UDF 对原生 DataFrame 操作的性能有很大影响。在考虑了更多之后,这是另一种不使用 UDF 的方法。一般的想法是用逗号替换所有不是你想要的文本,然后用逗号分割来创建你的最终值数组。如果您只想要数字,您可以更新正则表达式以将“ML”从捕获组中取出。

pattern = r'\d+(?:\.\d+)? ML'
split_pattern = r'.*?({pattern})'.format(pattern=pattern)
end_pattern = r'(.*{pattern}).*?$'.format(pattern=pattern)

df2 = df.withColumn('a', regexp_replace('str', split_pattern, '$1,'))
df3 = df2.withColumn('a', regexp_replace('a', end_pattern, '$1'))
df4 = df3.withColumn('a', split('a', r','))

推荐阅读