SKY-ALIN commented on code in PR #14282:
URL: https://github.com/apache/datafusion/pull/14282#discussion_r2012956967


##########
datafusion/functions/src/regex/regexpextract.rs:
##########
@@ -0,0 +1,322 @@
+// 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.
+
+use std::collections::hash_map::Entry;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use arrow::array::builder::GenericStringBuilder;
+use arrow::array::{
+    Array, ArrayRef, AsArray, OffsetSizeTrait, PrimitiveArray, StringArrayType,
+};
+use arrow::datatypes::{DataType, Int64Type};
+use datafusion_common::{
+    cast::as_generic_string_array, exec_err, internal_err, plan_err, 
DataFusionError,
+    Result,
+};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+    TypeSignature, Volatility,
+};
+use datafusion_macros::user_doc;
+use regex::Regex;
+
+#[user_doc(
+    doc_section(label = "Regular Expression Functions"),
+    description = "Extract a specific group matched by [regular 
expression](https://docs.rs/regex/latest/regex/#syntax). If the regex did not 
match, or the specified group did not match, an empty string is returned..",
+    syntax_example = "regexp_extract(str, regexp, idx)",
+    sql_example = r#"```sql
+            > select regexp_extract('100-200', '(\d+)-(\d+)', 1);
+            +---------------------------------------------------------------+
+            | regexp_extract(Utf8("100-200"),Utf8("(\d+)-(\d+)"), Int64(1)) |
+            +---------------------------------------------------------------+
+            | [100]                                                         |
+            +---------------------------------------------------------------+
+```
+"#,
+    standard_argument(name = "str", prefix = "String"),
+    standard_argument(name = "regexp", prefix = "Regular"),
+    standard_argument(name = "idx", prefix = "Integer")
+)]
+#[derive(Debug)]
+pub struct RegexpExtractFunc {
+    signature: Signature,
+}
+
+impl Default for RegexpExtractFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl RegexpExtractFunc {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::one_of(
+                vec![
+                    TypeSignature::Exact(vec![
+                        DataType::Utf8,
+                        DataType::Utf8,
+                        DataType::Int64,
+                    ]),
+                    TypeSignature::Exact(vec![
+                        DataType::LargeUtf8,
+                        DataType::LargeUtf8,
+                        DataType::Int64,
+                    ]),
+                    TypeSignature::Exact(vec![
+                        DataType::Utf8View,
+                        DataType::Utf8View,
+                        DataType::Int64,
+                    ]),
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for RegexpExtractFunc {
+    fn as_any(&self) -> &dyn std::any::Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "regexp_extract"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        use DataType::*;
+        Ok(match &arg_types[0] {
+            LargeUtf8 => LargeUtf8,
+            Utf8 => Utf8,
+            Utf8View => Utf8View,
+            Null => Null,
+            other => {
+                return plan_err!(
+                    "The regexp_extract function can only accept strings. Got 
{other}"
+                );
+            }
+        })
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let args_len = args.args.len();
+        if args_len != 3 {
+            return exec_err!("regexp_extract was called with {args_len} 
arguments, but it can accept only 3.");
+        }
+
+        let target = args.args[0].to_array(args.number_rows)?;
+        let pattern = args.args[1].to_array(args.number_rows)?;
+        let idx = args.args[2].to_array(args.number_rows)?;
+
+        let res = regexp_extract_func(&[target, pattern, idx])?;
+        Ok(ColumnarValue::Array(res))
+    }
+
+    fn documentation(&self) -> Option<&Documentation> {
+        self.doc()
+    }
+}
+
+fn regexp_extract_func(args: &[ArrayRef; 3]) -> Result<ArrayRef> {
+    match args[0].data_type() {
+        DataType::Utf8 => {
+            let target = as_generic_string_array::<i32>(&args[0])?;
+            let pattern = as_generic_string_array::<i32>(&args[1])?;
+            let idx = args[2].as_primitive::<Int64Type>();
+            regexp_extract::<i32>(target, pattern, idx)
+        }
+        DataType::LargeUtf8 => {
+            let target = as_generic_string_array::<i64>(&args[0])?;
+            let pattern = as_generic_string_array::<i64>(&args[1])?;
+            let idx = args[2].as_primitive::<Int64Type>();
+            regexp_extract::<i64>(target, pattern, idx)
+        }
+        DataType::Utf8View => {
+            let target = args[0].as_string_view();
+            let pattern = args[1].as_string_view();
+            let idx = args[2].as_primitive::<Int64Type>();
+            regexp_extract::<i32>(target, pattern, idx)
+        }
+        other => {
+            internal_err!("Unsupported data type {other:?} for function 
regexp_extract")
+        }
+    }
+}
+
+fn regexp_extract<'a, T>(
+    target: impl StringArrayType<'a>,
+    pattern: impl StringArrayType<'a>,
+    idx: &PrimitiveArray<Int64Type>,
+) -> Result<ArrayRef>
+where
+    T: OffsetSizeTrait,
+{
+    let mut builder = GenericStringBuilder::<T>::new();
+    let mut regex_cache: HashMap<&str, Regex> = HashMap::new();
+
+    for ((t_opt, p_opt), i_opt) in target.iter().zip(pattern.iter()).zip(idx) {
+        match (t_opt, p_opt, i_opt) {
+            (None, _, _) | (_, None, _) | (_, _, None) => {
+                // If any of arguments is null, the result will be null too
+                builder.append_null();
+            }
+            (Some(target_str), Some(pattern_str), Some(idx_val)) => {
+                if idx_val < 0 {
+                    return exec_err!("idx in regexp_extract can't be 
negative");
+                }
+
+                let re = match regex_cache.entry(pattern_str) {
+                    Entry::Occupied(occupied_entry) => 
occupied_entry.into_mut(),
+                    Entry::Vacant(vacant_entry) => {
+                        let compiled = Regex::new(pattern_str).map_err(|e| {
+                            DataFusionError::Execution(format!(
+                                "Can't compile regexp: {e}"
+                            ))
+                        })?;
+                        vacant_entry.insert(compiled)
+                    }
+                };
+
+                let caps_opt = re.captures(target_str);
+
+                match caps_opt {
+                    Some(caps) => {
+                        // If regexp matches string
+                        let group_idx = idx_val as usize;
+                        if group_idx < caps.len() {
+                            // If specified group index really exists
+                            if let Some(m) = caps.get(group_idx) {

Review Comment:
   No, it depends on a regular expression. It's not special for Rust regexp lib 
or any other implementations from other languages. I recommend reading a little 
about regex groups 
[here](https://learn.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions).
 I assume if a user uses `regexp_extract` function with `group_...` argument, 
they know what it is and how it works



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

To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to