![](/img/trans.png)
[英]How can I extract the numerical prefix of a string using REGEX_EXTRACT on Hive?
[英]How can i extract Dates from a string field in Hive using RegEx function
'2021 july (JNS) Accessory Fixtures: DELIVER BETWEEN 7/26/2021 and 8/6/2021'
預期結果:
Date1 : 7/26/2021
Date2 : 8/6/2021
例如像這樣:
select regexp_extract(str, '(?i)BETWEEN (\\d{1,2}/\\d{1,2}/\\d{4})',1) as date1,
regexp_extract(str, '(?i)AND (\\d{1,2}/\\d{1,2}/\\d{4})$',1) as date2
如果您需要將日期轉換為正確的格式 (yyyy-MM-dd),請使用 split 獲取數組中的所有日期元素,使用 lpad 添加零並連接:
with mydata as (
select '2021 july (JNS) Accessory Fixtures: DELIVER BETWEEN 7/26/2021 and 8/6/2021' str
)
select concat(date1[2],'-',lpad(date1[0],2,0),'-',lpad(date1[1],2,0)) as date1,
concat(date2[2],'-',lpad(date2[0],2,0),'-',lpad(date2[1],2,0)) as date2
from
(
select split(date1,'/') date1, split(date2,'/') date2 --arrays
from
(select regexp_extract(str, '(?i)BETWEEN (\\d{1,2}/\\d{1,2}/\\d{4})',1) as date1,
regexp_extract(str, '(?i)AND (\\d{1,2}/\\d{1,2}/\\d{4})$',1) as date2
from mydata
) s
)s
結果:
date1 date2
2021-07-26 2021-08-06
如果有不帶 BETWEEN 和 AND 的字符串,並且您想從字符串的開頭提取第一個和第二個日期,請使用以下命令:
select regexp_extract(str, '^.*(\\d{1,2}/\\d{1,2}/\\d{4}).*(\\d{1,2}/\\d{1,2}/\\d{4})',1) as date1,
regexp_extract(str, '^.*(\\d{1,2}/\\d{1,2}/\\d{4}).*(\\d{1,2}/\\d{1,2}/\\d{4})',2) as date2
您可以通過在第二組后添加 * 使第二個日期可選,即使字符串中不存在第二個日期,也會提取第一個日期:
select regexp_extract(str, '^.*(\\d{1,2}/\\d{1,2}/\\d{4}).*(\\d{1,2}/\\d{1,2}/\\d{4})*',1) as date1,
regexp_extract(str, '^.*(\\d{1,2}/\\d{1,2}/\\d{4}).*(\\d{1,2}/\\d{1,2}/\\d{4})',2) as date2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.