首页 > 解决方案 > SQL 使用 regexp_subtr 提取日期子字符串

问题描述

我有一个名为 signal_notes 的字段,其中包含如下字符串(这将是 signal_notes 的单个值):

"{ ^search_date^: ^2021-01-05^, 
^filing_date^: ^^, 
^expiry_date^: ^^, 
^other_liens^: ^^, 
^who_1st_positon^: ^^, 
^who_2nd_position^: ^^, 
^who_3rd_position^: ^^, 
^priority_from_1^: ^^, 
^priority_from_2^: ^^, 
^priority_from_3^: ^^, 
^notes^: ^^ 
^client_facing_notes^: ^^ 
 }"

有时,^expiry_date^行在 ^ 之间会有一个日期,格式为 'YYYY-MM-DD'。

理想情况下,我的新字段expiry_date格式为“YYYY-MM-DD”,带有来自signal_notes字段的日期字符串。

这是我到目前为止所得到的,但它什么也没返回。

select
(regexp_substr(signal_notes, 'expiry_date [0-9-]*' )) as expiry_date
from db

我也试过

(regexp_substr( signal_notes, '^expiry_date^: ^[0-9-]*^' )) as first_as_of_date_context

结果相同。

欢迎任何建议

标签: sqlamazon-redshiftregexp-substr

解决方案


如果我理解正确,您需要一个子表达式。这^是一种痛苦,一种解决方法是:

regexp_substr(signal_notes, '.expiry_date.: .([0-9-]*).', 1, 1, 'e')

这与您上次的尝试非常相似,只是它具有子表达式,因此它应该只返回日期。

您还应该能够\\用作转义字符:

regexp_substr(signal_notes, '\\^expiry_date\\^: \\^([0-9-]*)\\^', 1, 1, 'e')

推荐阅读