Omega359 commented on code in PR #14323:
URL: https://github.com/apache/datafusion/pull/14323#discussion_r1930885951


##########
datafusion/functions/src/regex/regexpsubstr.rs:
##########
@@ -0,0 +1,554 @@
+// 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.
+
+//! Regex expressions
+use arrow::array::{
+    Array, ArrayRef, AsArray, GenericStringArray, GenericStringBuilder, 
OffsetSizeTrait,
+};
+use arrow::datatypes::{DataType, Int64Type};
+use arrow::error::ArrowError;
+use datafusion_common::plan_err;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::as_generic_string_array, internal_err, DataFusionError, Result,
+};
+use datafusion_expr::scalar_doc_sections::DOC_SECTION_REGEX;
+use datafusion_expr::{ColumnarValue, Documentation, ScalarFunctionArgs, 
TypeSignature};
+use datafusion_expr::{ScalarUDFImpl, Signature, Volatility};
+use regex::Regex;
+use std::any::Any;
+use std::sync::{Arc, OnceLock};
+
+#[derive(Debug)]
+pub struct RegexpSubstrFunc {
+    signature: Signature,
+}
+
+impl Default for RegexpSubstrFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl RegexpSubstrFunc {
+    pub fn new() -> Self {
+        use DataType::{Int64, LargeUtf8, Utf8};
+        Self {
+            signature: Signature::one_of(
+                vec![
+                    // Planner attempts coercion to the target type starting 
with the most preferred candidate.
+                    // For example, given input `(Utf8View, Utf8)`, it first 
tries coercing to `(Utf8, Utf8)`.
+                    // If that fails, it proceeds to `(LargeUtf8, Utf8)`.
+                    TypeSignature::Exact(vec![Utf8, Utf8]),
+                    TypeSignature::Exact(vec![LargeUtf8, LargeUtf8]),
+                    TypeSignature::Exact(vec![Utf8, Utf8, Int64]),
+                    TypeSignature::Exact(vec![LargeUtf8, LargeUtf8, Int64]),
+                    TypeSignature::Exact(vec![Utf8, Utf8, Int64, Int64]),
+                    TypeSignature::Exact(vec![LargeUtf8, LargeUtf8, Int64, 
Int64]),
+                    TypeSignature::Exact(vec![Utf8, Utf8, Int64, Int64, Utf8]),
+                    TypeSignature::Exact(vec![
+                        LargeUtf8, LargeUtf8, Int64, Int64, LargeUtf8,
+                    ]),
+                    TypeSignature::Exact(vec![Utf8, Utf8, Int64, Int64, Utf8, 
Int64]),
+                    TypeSignature::Exact(vec![
+                        LargeUtf8, LargeUtf8, Int64, Int64, LargeUtf8, Int64,
+                    ]),
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for RegexpSubstrFunc {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "regexp_substr"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        Ok(arg_types[0].clone())
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let len = args
+            .args
+            .iter()
+            .fold(Option::<usize>::None, |acc, arg| match arg {
+                ColumnarValue::Scalar(_) => acc,
+                ColumnarValue::Array(a) => Some(a.len()),
+            });
+
+        let is_scalar = len.is_none();
+        let inferred_length = len.unwrap_or(1);
+        let args = args
+            .args
+            .iter()
+            .map(|arg| arg.to_array(inferred_length))
+            .collect::<Result<Vec<_>>>()?;
+
+        let result = regexp_subst_func(&args);
+        if is_scalar {
+            // If all inputs are scalar, keeps output as scalar
+            let result = result.and_then(|arr| 
ScalarValue::try_from_array(&arr, 0));
+            result.map(ColumnarValue::Scalar)
+        } else {
+            result.map(ColumnarValue::Array)
+        }
+    }
+
+    fn documentation(&self) -> Option<&Documentation> {
+        Some(get_regexp_substr_doc())
+    }
+}
+
+static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
+
+fn get_regexp_substr_doc() -> &'static Documentation {
+    DOCUMENTATION.get_or_init(|| {
+        Documentation::builder(
+            DOC_SECTION_REGEX,
+            "Returns the substring that matches a [regular 
expression](https://docs.rs/regex/latest/regex/#syntax) within a string.",
+            "regexp_substr(str, regexp[, position[, occurrence[, flags[, 
group_num]]]])")
+            .with_sql_example(r#"```sql
+            > select regexp_substr('Köln', '[a-zA-Z]ö[a-zA-Z]{2}');
+            +---------------------------------------------------------+
+            | regexp_substr(Utf8("Köln"),Utf8("[a-zA-Z]ö[a-zA-Z]{2}")) |
+            +---------------------------------------------------------+
+            | Köln                                                    |
+            +---------------------------------------------------------+
+            SELECT regexp_substr('aBc', '(b|d)', 1, 1, 'i');
+            +---------------------------------------------------+
+            | regexp_substr(Utf8("aBc"),Utf8("(b|d)"), Int32(1), Int32(1), 
Utf8("i")) |
+            +---------------------------------------------------+
+            | B                                                 |
+            +---------------------------------------------------+
+```
+Additional examples can be found 
[here](https://docs.snowflake.com/en/sql-reference/functions/regexp_substr#examples)
+"#)
+            .with_standard_argument("str", Some("String"))
+            .with_argument("regexp", "Regular expression to match against.
+            Can be a constant, column, or function.")
+            .with_argument("position", "Number of characters from the 
beginning of the string where the function starts searching for matches. 
Default: 1")
+            .with_argument("occurrence", "Specifies the first occurrence of 
the pattern from which to start returning matches.. Default: 1")
+            .with_argument("flags",
+                           r#"Optional regular expression flags that control 
the behavior of the regular expression. The following flags are supported:
+  - **i**: case-insensitive: letters match both upper and lower case
+  - **c**: case-sensitive: letters match upper or lower case. Default flag
+  - **m**: multi-line mode: ^ and $ match begin/end of line
+  - **s**: allow . to match \n
+  - **e**: extract submatches (for Snowflake compatibility)
+  - **R**: enables CRLF mode: when multi-line mode is enabled, \r\n is used
+  - **U**: swap the meaning of x* and x*?"#)
+            .with_argument("group_num", "Specifies which group to extract. 
Groups are specified by using parentheses in the regular expression.")
+            .build()
+    })
+}
+
+fn regexp_subst_func(args: &[ArrayRef]) -> Result<ArrayRef> {
+    match args[0].data_type() {
+        DataType::Utf8 => regexp_substr::<i32>(args),
+        DataType::LargeUtf8 => regexp_substr::<i64>(args),
+        other => {
+            internal_err!("Unsupported data type {other:?} for function 
regexp_substr")
+        }
+    }
+}
+pub fn regexp_substr<T: OffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+    let args_len = args.len();
+    let get_int_arg = |index: usize, name: &str| -> Result<Option<i64>> {
+        if args_len > index {
+            let arg = args[index].as_primitive::<Int64Type>();
+            if arg.is_empty() {
+                return plan_err!(
+                    "regexp_substr() requires the {:?} argument to be an 
integer",
+                    name
+                );
+            }
+            Ok(Some(arg.value(0)))
+        } else {
+            Ok(None)
+        }
+    };
+
+    let values = as_generic_string_array::<T>(&args[0])?;
+    let regex = Some(as_generic_string_array::<T>(&args[1])?.value(0));
+    let start = get_int_arg(2, "position")?;
+    let occurrence = get_int_arg(3, "occurrence")?;
+    let flags = if args_len > 4 {
+        let flags = args[4].as_string::<T>();
+        if flags.iter().any(|s| s == Some("g")) {
+            return plan_err!("regexp_substr() does not support the \"global\" 
option");
+        }
+        Some(flags.value(0))
+    } else {
+        None
+    };
+
+    let group_num = get_int_arg(5, "group_num")?;
+
+    let result =
+        regexp_substr_inner::<T>(values, regex, start, occurrence, flags, 
group_num)?;
+    Ok(Arc::new(result))
+}
+
+fn regexp_substr_inner<T: OffsetSizeTrait>(
+    values: &GenericStringArray<T>,
+    regex: Option<&str>,
+    start: Option<i64>,
+    occurrence: Option<i64>,
+    flags: Option<&str>,
+    group_num: Option<i64>,
+) -> Result<ArrayRef> {
+    let regex = match regex {
+        None | Some("") => {
+            return 
Ok(Arc::new(GenericStringArray::<T>::new_null(values.len())))
+        }
+        Some(regex) => regex,
+    };
+    let regex = compile_regex(regex, flags)?;
+    let mut builder = GenericStringBuilder::<T>::new();
+
+    values.iter().try_for_each(|value| {
+        match value {
+            Some(value) => {
+                // Skip characters from the beginning
+                let cleaned_value = if let Some(start) = start {
+                    if start < 1 {
+                        return 
Err(DataFusionError::from(ArrowError::ComputeError(
+                            "regexp_count() requires start to be 1 
based".to_string(),

Review Comment:
   ```suggestion
                               "regexp_substr() requires start to be 1 
based".to_string(),
   ```



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