sweb commented on a change in pull request #9428: URL: https://github.com/apache/arrow/pull/9428#discussion_r602892170
########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,147 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + ArrayRef, GenericStringArray, GenericStringBuilder, ListBuilder, + StringOffsetSizeTrait, +}; +use crate::error::{ArrowError, Result}; +use std::collections::HashMap; + +use std::sync::Arc; + +use regex::Regex; + +/// Extract all groups matched by a regular expression for a given String array. +pub fn regexp_match<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + regex_array: &GenericStringArray<OffsetSize>, + flags_array: Option<&GenericStringArray<OffsetSize>>, +) -> Result<ArrayRef> { + let mut patterns: HashMap<String, Regex> = HashMap::new(); + let builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + let mut list_builder = ListBuilder::new(builder); + + let complete_pattern = match flags_array { + Some(flags) => Box::new(regex_array.iter().zip(flags.iter()).map( + |(pattern, flags)| { + pattern.map(|pattern| match flags { + Some(value) => format!("(?{}){}", value, pattern), + None => pattern.to_string(), + }) + }, + )) as Box<dyn Iterator<Item = Option<String>>>, + None => Box::new( + regex_array + .iter() + .map(|pattern| pattern.map(|pattern| pattern.to_string())), + ), + }; + array + .iter() + .zip(complete_pattern) + .map(|(value, pattern)| { + match (value, pattern) { + (Some(value), Some(pattern)) => { + let existing_pattern = patterns.get(&pattern); + let re = match existing_pattern { + Some(re) => re.clone(), + None => { + let re = Regex::new(pattern.as_str()).map_err(|e| { + ArrowError::ComputeError(format!( + "Regular expression did not compile: {:?}", + e + )) + })?; + patterns.insert(pattern, re.clone()); + re + } + }; + match re.captures(value) { + Some(caps) => { + for m in caps.iter().skip(1) { + if let Some(v) = m { + list_builder.values().append_value(v.as_str())?; + } + } + list_builder.append(true)? + } + None => { + list_builder.values().append_value("")?; + list_builder.append(true)? + } + } + } + _ => list_builder.append(false)?, + } + Ok(()) + }) + .collect::<Result<Vec<()>>>()?; + Ok(Arc::new(list_builder.finish())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::array::{ListArray, StringArray}; + + #[test] + fn match_single_group() -> Result<()> { Review comment: @seddonm1 First: I am very impressed that you know of this case. My original implementation returned an empty List, without an item. Do you know whether Postgres actually returns a quoted empty string? I am asking because ``` SELECT regexp_match('foobarbequebaz', '(bar)(beque)'); => {bar,beque} ``` so I am not sure what to make of the quotes, since strings are not returned with quotes or is this just a special case when the string is empty? Regardless, I added special case for the empty string pattern -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org