Redshift REGEXP_SUBSTR 获取匹配项的最后一次出现

Redshift REGEXP_SUBSTR get last occurrence of a match

我在使用 listagg 方法获得的按时间升序排序的列值中有所有类型的页面事件列表。 listagg(page,';') within group (order by time)

我想获取匹配正则表达式的最后一个匹配项的出现 regexp_substr(event_list,'/step[0-9]+[^;]*')

根据文档 "A positive integer that indicates the position within source_string to begin searching. The position is based on the number of characters, not bytes, so that multibyte characters are counted as single characters. The default is 1. If position is less than 1, the search begins at the first character of source_string. If position is greater than the number of characters in source_string, the result is source_string."

基于此,我需要知道我不知道的确切发生次数。 在这种情况下如何获得最后一场比赛? 例如: /step1;somethging;somethig;/step2;something;/step3;something;

我要配step3.

PS:按时间描述排序并获得第一个匹配项不是此处的选项。

使用 regexp_count to determine how many matches there are (n) & then use regexp_substr 获得第 n 个匹配项。

select 
  '/step1;somethging;somethig;/step2;something;/step3;something;' string
, '/step[0-9]+[^;]*' pat
, regexp_count(string, pat) n
, regexp_substr(string, pat, 1, n) last_part

输出:

                                                       string                pat    n    last_part
/step1;somethging;somethig;/step2;something;/step3;something;   /step[0-9]+[^;]*    3       /step3

如果 / 可以被视为分隔符,那么您也可以采用以下策略

反转字符串,用 / 拆分并取第一部分。再次反转,前缀 / 并应用正则表达式提取步骤:

示例:

select 
  '/step1;somethging;somethig;/step2;something;/step3;something;' string
, '/' || reverse(split_part(reverse(string), '/', 1)) last_part
, regexp_substr(last_part, '/step[0-9]+[^;]*') extract_step

输出:

                                                       string           last_part   extract_step 
/step1;somethging;somethig;/step2;something;/step3;something;   /step3;something;         /step3