sweb commented on a change in pull request #9428:
URL: https://github.com/apache/arrow/pull/9428#discussion_r588464398



##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -70,6 +71,16 @@ pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> 
{
     Ok(builder.finish())
 }
 
+/// extract a specific group from a string column, using a regular expression
+pub fn regexp_extract(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let pattern_expr = args[1].as_any().downcast_ref::<StringArray>().unwrap();
+    let pattern = pattern_expr.value(0);
+    let idx_expr = args[2].as_any().downcast_ref::<Int64Array>().unwrap();
+    let idx = idx_expr.value(0) as usize;

Review comment:
       Absolutely, I did this because I am not sure, how I can get from 
`ArrayRef` to `ScalarVariant` - I am looking for something like the following:
   
   ```
       let pattern_expr = 
args[1].as_any().downcast_ref::<ScalarValue>().unwrap();
       if let ScalarValue::Utf8(Some(pattern)) = pattern_expr {
           compute::regexp_match(args[0].as_ref(), pattern)
               .map_err(DataFusionError::ArrowError)
       } else {
           Err(DataFusionError::Internal("This is wrong".to_string()))
       }
   ```

##########
File path: rust/arrow/src/compute/kernels/regexp.rs
##########
@@ -0,0 +1,117 @@
+// 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::{
+    Array, ArrayRef, GenericStringArray, GenericStringBuilder, 
LargeStringArray,
+    StringArray, StringOffsetSizeTrait,
+};
+use crate::datatypes::DataType;
+use crate::error::{ArrowError, Result};
+
+use std::sync::Arc;
+
+use regex::Regex;
+
+fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>(
+    array: &GenericStringArray<OffsetSize>,
+    re: &Regex,
+    idx: usize,
+) -> Result<ArrayRef> {
+    let mut builder: GenericStringBuilder<OffsetSize> = 
GenericStringBuilder::new(0);
+
+    for maybe_value in array.iter() {
+        match maybe_value {
+            Some(value) => match re.captures(value) {
+                Some(caps) => {
+                    let m = caps.get(idx).ok_or_else(|| {
+                        ArrowError::ComputeError(format!(
+                            "Regexp has no group with index {}",
+                            idx
+                        ))
+                    })?;
+                    builder.append_value(m.as_str())?
+                }
+                None => builder.append_null()?,
+            },
+            None => builder.append_null()?,
+        }
+    }
+    Ok(Arc::new(builder.finish()))
+}
+
+/// Extracts a specific group matched by a regular expression for a given 
String array.
+/// Group index 0 returns the whole match, index 1 returns the first group and 
so on. Please
+/// refer to regex crate for details on pattern specifics.
+pub fn regexp_extract(array: &Array, pattern: &str, idx: usize) -> 
Result<ArrayRef> {
+    let re = Regex::new(pattern).map_err(|e| {
+        ArrowError::ComputeError(format!("Regular expression did not compile: 
{:?}", e))
+    })?;
+    match array.data_type() {
+        DataType::LargeUtf8 => generic_regexp_extract(
+            array
+                .as_any()
+                .downcast_ref::<LargeStringArray>()
+                .expect("A large string is expected"),
+            &re,
+            idx,
+        ),
+        DataType::Utf8 => generic_regexp_extract(
+            array
+                .as_any()
+                .downcast_ref::<StringArray>()
+                .expect("A string is expected"),
+            &re,
+            idx,
+        ),
+        _ => Err(ArrowError::ComputeError(format!(
+            "regexp_extract does not support type {:?}",
+            array.data_type()
+        ))),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn extract_single_group() -> Result<()> {
+        let values = vec!["abc-005-def", "X-7-5", "X545"];
+        let array = StringArray::from(values);
+        let pattern = r".*-(\d*)-.*";
+        let actual = regexp_extract(&array, pattern, 1)?;
+        let expected = StringArray::from(vec![Some("005"), Some("7"), None]);
+        let result = actual.as_any().downcast_ref::<StringArray>().unwrap();
+        assert_eq!(&expected, result);
+        Ok(())
+    }
+
+    #[test]
+    fn no_matches() -> Result<()> {
+        let values = vec!["abc", "X::50::00", "X545"];
+        let array = StringArray::from(values);
+        let pattern = r".*-(\d*)-.*";
+        let actual = regexp_extract(&array, pattern, 1)?;
+        let expected = StringArray::from(vec![None, None, None]);
+        let result = actual.as_any().downcast_ref::<StringArray>().unwrap();
+        assert_eq!(&expected, result);
+        Ok(())
+    }

Review comment:
       Done




----------------------------------------------------------------
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


Reply via email to