简体   繁体   中英

SQL RegEx: How to extract the date from this string

How do I pull 2018.11.06 from this string using RegEx

"NL-SAS-US-2018.11.06.Nov 6 2018 - SL Email - US Newsletter"

The characters can change in various ways and lengths but there will always be a date in the format of YYYY.MM.DD at some point in the string

Table:
在此处输入图片说明

Here's my current solution but I think there's a better way to do it?

SELECT *, 
REGEXP_EXTRACT(email_name, '([0-9]+)') AS email_name
FROM
    (SELECT REPLACE(email_name, ".", "") AS email_name
    FROM emailsTable)

This gives me "20181106"

Thanks

Moving "the fourth bird"'s comment into a full answer:

SELECT REGEXP_REPLACE(
  "NL-SAS-US-2018.11.06.Nov 6 2018 - SL Email - US Newsletter"
  , r'.*\b(\d{4})\.(\d{2})\.(\d{2})\b.*'
  , r'\1\2\3')

20181106

Below example for BigQuery Standard SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'NL-SAS-US-2018.11.06.Nov 6 2018 - SL Email - US Newsletter' email_name
)
SELECT REGEXP_EXTRACT(email_name, r'([12]\d{3}.(?:0[1-9]|1[0-2]).(?:0[1-9]|[12]\d|3[01]))') email_date
FROM `project.dataset.table`

with result

Row email_date   
1   2018.11.06   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM