Implement Spark-compatible `regexp_replace`
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 25/100
Línea de trabajo
Start by reading the existing functions in crates/spark/src/function/string/ and the shared Java-regex compatibility helper proposed for rlike, since this implementation depends on it. Use DataFusion's datafusion/functions/src/regex/regexpreplace.rs only as a reference for what not to wrap, and compare against Spark's RegExpReplace in regexpExpressions.scala. Add crates/sqllogictest/test_files/string/regexp_replace.slt covering position offsets in UTF-16 units, Java replacement syntax and the error cases; done means those tests match Spark's golden output.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Part of #174 and apache/datafusion-comet#7300.
What the function does
regexp_replace(str, regexp, rep[, position]) replaces every substring of str that matches the Java regular expression regexp with rep, starting the search at the 1-based position (default 1). Spark loops Matcher.find() / appendReplacement / appendTail, so all matches are replaced (there is no "first only" mode and no flags argument). Available since 1.5.0.
str, regexp and rep are implicitly cast to STRING and position to INT. position must be foldable and greater than 0, otherwise analysis fails. Result type is the type of str (STRING, with its collation in 4.0+). NULL if any argument is NULL (including a NULL position).
Examples
SELECT regexp_replace('100-200', '(\\d+)', 'num');
-- num-num
SELECT regexp_replace('100-200', r'(\d+)', 'num');
-- num-num
SELECT regexp_replace('healthy, wealthy, and wise', '\\w+thy', 'something', 2);
-- hsomething, something, and wise
SELECT regexp_replace('healthy, wealthy, and wise', '\\w+thy', 'something', 8);
-- healthy, something, and wise
SELECT regexp_replace('healthy, wealthy, and wise', '\\w', 'something', 26);
-- healthy, wealthy, and wissomething
SELECT regexp_replace('healthy, wealthy, and wise', '\\w', 'something', 27);
-- healthy, wealthy, and wise
SELECT regexp_replace('healthy, wealthy, and wise', '\\w', 'something', null);
-- NULL
SELECT regexp_replace('', '^$', '<empty string>');
-- <empty string>
SELECT regexp_replace('healthy, wealthy, and wise', '\\w+thy', 'something', 0);
-- error DATATYPE_MISMATCH.VALUE_OUT_OF_RANGE
Edge cases to test
- NULL in each of the four arguments, literal and column, returns NULL.
position: 0 or negative fails analysis withDATATYPE_MISMATCH.VALUE_OUT_OF_RANGE(valueRange(0, 2147483647]); a non-foldablepositionfails withDATATYPE_MISMATCH.NON_FOLDABLE_INPUT. Ifposition - 1 >= length(str)(andposition != 1) the input is returned unchanged. Withstr = ''and position 1 the pattern is still applied (see the^$example).positionand the length check are in UTF-16 code units (String.length,Matcher.region), not code points. A supplementary character before the start shifts the position:regexp_replace('😀ab', 'a', 'X', 3)starts ata(the emoji is two UTF-16 units) and returns😀Xb, while a code-point-based port returns😀ab.- The search region uses Java's default anchoring bounds, so
^matches at the region start:regexp_replace('abc', '^b', 'X', 2)returnsaXc. Rust'sfind_atdoes not treat the start offset as^, so a naive port returnsabc. - Empty pattern: matches at every position.
regexp_replace('abc', '', '-')gives-a-b-c-. - Empty-match iteration: Java reports an empty match immediately after a non-empty match; the
regexcrate does not (itstestdata/empty.tomlgives 3 matches forb|onabc, Java finds 4). Soregexp_replace('abc', 'b|', '-')differs. - Replacement string uses Java
Matcher.appendReplacementsyntax:$nand${name}refer to groups:regexp_replace('100-200', '(\\d+)', '<$1>')gives<100>-<200>.\escapes the next character, so\$is a literal$and\1is a literal1(not a backreference as in DataFusion'sregexp_replace).- Java parses
$12as group 12 only if it exists, otherwise group 1 followed by2;$1ais group 1 followed bya. Rust treats$1aas a group named1aand$12as group 12, and substitutes an empty string for missing groups. - A reference to a missing group or a trailing
$fails. 4.0+:INVALID_REGEXP_REPLACE(SQLSTATE 22023)Could not perform regexp_replace for source = "first last", pattern = "(?<first>[a-zA-Z]+) (?<last>[a-zA-Z]+)", replacement = "$3 $1" and position = 1.(cause message containsNo group 3,StringFunctionsSuite). 3.4/3.5 throw the raw JavaIndexOutOfBoundsException/IllegalArgumentException.
- Invalid pattern:
INVALID_PARAMETER_VALUE.PATTERN, e.g.regexp_replace('', '[a\\d]{0, 2}', 'x')(StringFunctionsSuite, SPARK-44905). Applies to literal and column patterns. - Column patterns and column replacements (Spark caches the last pattern and replacement; results must not leak between rows).
spark.sql.parser.escapedStringLiterals(default false) changes parsing of the SQL literals forregexpandrepbefore they reach the function. In.sltfiles, DataFusion keeps backslashes literal, so Spark'(\\d+)'is'(\d+)'.- Java vs Rust pattern divergences (decline or test each): lookaround / backreferences / atomic groups / possessive quantifiers (Java only); ASCII
\d\w\sin Java vs Unicode in Rust (regexp_replace('a\u0663', '\\d', 'X')(U+0663 ARABIC-INDIC DIGIT THREE) is unchanged in Spark);.excludes\r\u0085\u2028\u2029in Java;$matches before a final line terminator in Java (regexp_replace('abc\n', 'c$', 'X')givesabX\n);(?i)is ASCII-only in Java (U+212A KELVIN SIGN does not match(?i)k); different inline flag letters (U,u,d); Java-only\Q..\E,\h,\R,\Z, octal; Rust-only(?P<n>),\<,[[:alpha:]]. UTF8_LCASEcollation (4.0+) compiles withCASE_INSENSITIVE | UNICODE_CASE.
Differences across Spark versions
- 4.0: replacement errors wrapped as
INVALID_REGEXP_REPLACE(raw Java exceptions in 3.4/3.5); collation-aware input types; return type followsstr(was always STRING). DATATYPE_MISMATCH.NON_FOLDABLE_INPUTinputNameispositionin 3.4/3.5 and`position`in 4.0+.
Implementation notes
- Spark:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala,RegExpReplace(pattern compile inRegExpUtils.getPatternAndLastRegex). - DataFusion core
regexp_replace(str, regexp, replacement[, flags])(datafusion/functions/src/regex/regexpreplace.rs) differs in every respect that matters: the 4th argument is flags, only the first match is replaced unless thegflag is given,\1in the replacement is rewritten to${1}, and it uses Rust regex syntax. It should not be wrapped as-is. - Use the shared Java-regex compatibility helper proposed for
rlike(verified subset, decline otherwise, with the decision made at planning time for literal patterns). Also translate the replacement string from Java syntax and decline replacement strings whose meaning cannot be reproduced exactly (escape sequences, ambiguous$nn). - Belongs in
crates/spark/src/function/string/. Addcrates/sqllogictest/test_files/string/regexp_replace.sltand document with#[user_doc].
This issue was generated by an LLM (Claude) from the Apache Spark source code and tests. Examples come from Spark's ExpressionDescription examples, test suites and .sql.out golden files, but please verify them against Spark before relying on them.
- Lenguaje dominante
- Rust
- Estrellas
- 7
- Forks
- 15
- Merge medio
- 16 h 43 min
- PR fusionados (30 d)
- 26
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de apache/datafusion-spark
-
enhancement
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
apache/datafusion-spark#287 ·
Los mantenedores suelen responder en 1 día
-
enhancement good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
apache/datafusion-spark#266 ·
Los mantenedores suelen responder en 1 día
-
[Bug] make_dt_interval returns NULL for more than about 1.49 million days, Spark returns the intervalPosiblemente ocupada @Subodh-17 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
apache/datafusion-spark#109 ·
Los mantenedores suelen responder en 1 día
-
enhancement
Dificultad 5/5 Más de una semana Aptitud para principiantes 18/100
apache/datafusion-spark#299 ·
Los mantenedores suelen responder en 1 día
-
enhancement
Dificultad 4/5 3-5 días Aptitud para principiantes 35/100
apache/datafusion-spark#298 ·
Los mantenedores suelen responder en 1 día
Todos los issues de apache/datafusion-spark
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
storytold/photocraft#15232 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
suhina-daw/suhina-daw#1477 ·
Los mantenedores suelen responder en 1 día
-
parity priority: low ui
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
storytold/pdfcraft#7483 · 1 comentario ·
Los mantenedores suelen responder en 2 días
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
IngvarConsulting/unica#3097 ·
Los mantenedores suelen responder en 1 día
-
enhancement in-progress
Dificultad 1/5 Menos de una hora Aptitud para principiantes 64/100