雪花字符串替换javascript udf

时间:2021-04-27 23:26:37

标签: javascript snowflake-cloud-data-platform

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

这是我的 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?'

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

因为在 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?'
> 

答案 1 :(得分:0)

这是为将来遇到此问题的人准备的工作版本:

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