【问题标题】:Using regex in SQL (Amazon Redshift) to extract tag在 SQL (Amazon Redshift) 中使用正则表达式提取标签
【发布时间】:2019-03-20 23:47:56
【问题描述】:

我已经尝试了几个小时来解决这个问题,但被卡住了。

我正在尝试提取此子字符串

dg

从这样的事情

agent/bond,am/dg,day/sunday,man/woman,exemption/yes,account/true

am/dg,agent/bond,day/sunday,man/woman,exemption/yes,account/true

在 Redshift 中使用正则表达式。

我接近了regexp_substr(tags,'[(^am\/$)][^,]+'),但它并没有完全奏效。

感谢您提供的任何帮助。

【问题讨论】:

  • 您使用的是什么版本的 Redshift?
  • 不确定@TimBiegeleisen

标签: sql regex amazon-redshift


【解决方案1】:

我们或许可以在此处将REGEXP_REPLACE 与捕获组一起使用:

SELECT
    REGEXP_REPLACE(input, '.*\yam/([^,]+).*', '$1')
FROM yourTable;

【讨论】:

  • @DavidGarsia 当您运行我的更新查询时到底发生了什么?
  • 你的函数的输出等于输入。
  • 尝试使用$1代替\1
  • REGEXP_REPLACE(tags, '.*am/([^,]+).*', '$1')(所以没有\y$)有效!谢谢!
  • 你知道一个可以测试 Redshift (SQL) 正则表达式的好网站吗?
【解决方案2】:

SUBSTRING 以及正则表达式 look-behindlook-ahead positive 的这种方式怎么样?

说明:捕获前面有am/和后面有,的标签,即dg

SELECT
 SUBSTRING (
 'agent/bond,am/dg,day/sunday,man/woman,exemption/yes,account/true',
 '(?<=am/)(.*?)(?=,)'
 ) as tag;

SELECT
 SUBSTRING (
 'am/dg,agent/bond,day/sunday,man/woman,exemption/yes,account/true',
 '(?<=am/)(.*?)(?=,)'
 ) as tag;

【讨论】:

  • account/true,am/dg 这样的输入呢?
  • 不幸的是,子字符串函数似乎不适用于(我的版本)Redshift。如果我将函数更改为 regexp_replace,我会收到以下错误:Invalid preceding regular expression prior to repetition operator. The error occured while parsing the regular expression fragment: '(?&gt;&gt;&gt;HERE&gt;&gt;&gt;&lt;=am/)(.*?'. 所以我认为在我的 Redshift 版本中,不支持后视和前瞻。 (我也逃脱了斜线(/ => \/,这并没有解决问题。)
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2010-09-23
  • 2019-01-07
相关资源
最近更新 更多