【问题标题】:Regex_replace in snowflake using patternRegex_replace 在雪花中使用模式
【发布时间】:2022-01-07 06:32:04
【问题描述】:

我正在寻找一种正则表达式模式,它将删除文章(a、an、the)、特殊字符(;、:、% 等)并扩展缩写(inc.-> 'incorporation', & -> 'and ' 等)在雪花中。我可以在雪花中做到这一点,但它并不完全正确。下面是我的代码。问题是我想给出模式(例如,'a good book' 的输出应该是 'good book' 但字符串 'give a book' 应该保留为

'''
select REGEXP_REPLACE((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((
select REGEXP_REPLACE ((


select REGEXP_REPLACE (

  
  (select REGEXP_REPLACE(concat (' ', lower('a book of the great man'), ' '), '(^an )|(^the )| 
  (^a )'))
  , '\\.|\\,|\\(|\\)|\\!|\\\\|/|£|\\$|%|\\^|\\*|-|\\+|=|_|{|}|\\[|\\]|#|~|;|:|''|`|@|<|>|\\?| 
 ¬|\\|')

  ), ' & ', ' and ')
  ), ' ltd ', ' limited ')

  ), '', '')
  '''

【问题讨论】:

  • 所以,要求从语句的开头删除文章,这就是我从您发布的示例中理解的。对于特殊字符,它需要从任何出现或位置中删除?
  • 是的,Srinath,没错

标签: regex snowflake-cloud-data-platform


【解决方案1】:

我建议你写一个 UDF(JavaScript 或 Java),而不是使用 REGEXP_REPLACE,并使用 JavaScript(或 java)的正则表达式。它将更加清洁和可维护。

https://docs.snowflake.com/en/sql-reference/user-defined-functions.html

这是一个示例函数:

CREATE OR REPLACE FUNCTION transform_text (STR VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS $$
  var abbreviations = { "inc.": "incorporation", "&": "and" };

  // remove articles from the beginning
  var Result = STR.replace( /^(a|an|the) /i, "" );

  // remove the special characters
  Result = Result.replace( /(;|,|:|%)/g, "" );

  // convert abbreviations
  for (var abv in abbreviations) Result = Result.replace( abv, abbreviations[abv] );

  return (Result);
$$
;

select transform_text( 'A good, a:; bo%ok & hoyd inc.' ) as Result;


+------------------------------------+
|               RESULT               |
+------------------------------------+
| good a book and hoyd incorporation |
+------------------------------------+

【讨论】:

    【解决方案2】:

    对 Gokhan 的出色回答进行了一些调整。

    1. 在删除特殊字符之前转换缩写词
    2. 使用 ^ 不是这些方法之一更容易删除特殊字符
    3. 使用 \b 来捕获文章的单词

    CREATE OR REPLACE FUNCTION transform_text_2 (STR VARCHAR)
    RETURNS VARCHAR
    LANGUAGE JAVASCRIPT
    AS $$
      var abbreviations = { "inc.": "incorporation", "&": "and" };
    
      // remove articles from the beginning
      var Result = STR.replace( /\b(an?|the)\b /i, "" );
    
      // convert abbreviations
      for (var abv in abbreviations) Result = Result.replace( abv, abbreviations[abv] );
    
      // remove the special characters
      Result = Result.replace( /[^A-Za-z0-9 ]/g, "" );
    
    
      return (Result);
    $$
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多