首页 > 解决方案 > 雪花字符串替换javascript udf

问题描述

尝试在 Snowflake 中使用 Javascript 的String.prototype.replace()函数,因为显然 Snowflake 的regex_replace函数缺乏某些功能,例如 ast(向前/向后)环顾四周。

这是我的 Javascript UDF 尝试:

CREATE OR REPLACE FUNCTION REXP_REPLACE_ME(subject TEXT, pattern TEXT, replacement TEXT)
  RETURNS string
  LANGUAGE JAVASCRIPT
  AS
  $$
    const p = SUBJECT;
    const regex = PATTERN;
    return p.replace(regex, REPLACEMENT);
  $$
  ;

但是,当我尝试使用string.prototype.replace()上面链接的文档中提供的示例执行时。我没有得到预期的结果:


SELECT REXP_REPLACE_ME('The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?', '/Dog/i', 'cat')

//expected output: 'The quick brown fox jumps over the lazy ferret. If the cat reacted, was it really lazy?'
//actual output: 'The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?'

有任何想法吗?

标签: javascriptsnowflake-cloud-data-platform

解决方案


因为在 Javascript 中,正则表达式不是横向字符串,它是它自己的东西。

> a = 'The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?';
'The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?'
> b = a.replace('/Dog/i', 'cat');
'The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?'
> b = a.replace(/Dog/i, 'cat');
'The quick brown fox jumps over the lazy ferret. If the cat reacted, was it really lazy?'
> 

推荐阅读