@@ -19,7 +19,6 @@ use crate::types::evaluator::binary_create;
1919use crate :: types:: tuple:: TupleLike ;
2020use crate :: types:: value:: { DataValue , Utf8Type } ;
2121use crate :: types:: { CharLengthUnits , LogicalType } ;
22- use regex:: Regex ;
2322use std:: borrow:: Cow ;
2423use std:: cmp;
2524use std:: cmp:: Ordering ;
@@ -228,22 +227,7 @@ impl ScalarExpression {
228227 . map ( String :: from)
229228 . unwrap_or_default ( ) ;
230229 }
231- let trim_regex = match trim_where {
232- Some ( TrimWhereField :: Both ) | None => Regex :: new ( & format ! (
233- r"^(?:{0})*([\w\W]*?)(?:{0})*$" ,
234- regex:: escape( & trim_what)
235- ) )
236- . unwrap ( ) ,
237- Some ( TrimWhereField :: Leading ) => {
238- Regex :: new ( & format ! ( r"^(?:{0})*([\w\W]*?)" , regex:: escape( & trim_what) ) )
239- . unwrap ( )
240- }
241- Some ( TrimWhereField :: Trailing ) => {
242- Regex :: new ( & format ! ( r"([\w\W]*?)(?:{0})*$" , regex:: escape( & trim_what) ) )
243- . unwrap ( )
244- }
245- } ;
246- let string_trimmed = trim_regex. replace_all ( string, "$1" ) . to_string ( ) ;
230+ let string_trimmed = trim_string ( string, & trim_what, * trim_where) ;
247231
248232 Ok ( DataValue :: Utf8 {
249233 value : string_trimmed,
@@ -360,6 +344,31 @@ impl ScalarExpression {
360344 }
361345}
362346
347+ fn trim_string ( value : & str , trim_what : & str , trim_where : Option < TrimWhereField > ) -> String {
348+ if trim_what. is_empty ( ) {
349+ return value. to_string ( ) ;
350+ }
351+
352+ let mut trimmed = value;
353+ if matches ! (
354+ trim_where,
355+ Some ( TrimWhereField :: Leading | TrimWhereField :: Both ) | None
356+ ) {
357+ while let Some ( rest) = trimmed. strip_prefix ( trim_what) {
358+ trimmed = rest;
359+ }
360+ }
361+ if matches ! (
362+ trim_where,
363+ Some ( TrimWhereField :: Trailing | TrimWhereField :: Both ) | None
364+ ) {
365+ while let Some ( rest) = trimmed. strip_suffix ( trim_what) {
366+ trimmed = rest;
367+ }
368+ }
369+ trimmed. to_string ( )
370+ }
371+
363372#[ cfg( test) ]
364373mod tests {
365374 use super :: * ;
@@ -407,4 +416,23 @@ mod tests {
407416 assert_eq ! ( expr. eval:: <& [ DataValue ] >( None ) ?, DataValue :: Boolean ( false ) ) ;
408417 Ok ( ( ) )
409418 }
419+
420+ #[ test]
421+ fn trim_string_removes_requested_sides ( ) {
422+ assert_eq ! ( trim_string( "xxhelloxx" , "x" , None ) , "hello" ) ;
423+ assert_eq ! (
424+ trim_string( "xxhelloxx" , "x" , Some ( TrimWhereField :: Both ) ) ,
425+ "hello"
426+ ) ;
427+ assert_eq ! (
428+ trim_string( "xxhelloxx" , "x" , Some ( TrimWhereField :: Leading ) ) ,
429+ "helloxx"
430+ ) ;
431+ assert_eq ! (
432+ trim_string( "xxhelloxx" , "x" , Some ( TrimWhereField :: Trailing ) ) ,
433+ "xxhello"
434+ ) ;
435+ assert_eq ! ( trim_string( "ababhelloab" , "ab" , None ) , "hello" ) ;
436+ assert_eq ! ( trim_string( "hello" , "" , None ) , "hello" ) ;
437+ }
410438}
0 commit comments