首页 > 解决方案 > 在同一表达式中重新排序 RegEx 捕获组

问题描述

我有这种时间戳格式的日志文件:[04/Apr/2021:12:21:24 +0000]

此 RegEx 匹配此格式:

\[([0-9]{2})\/([A-Za-z]{3})\/([0-9]{4}):([0-9]{2}:[0-9]{2}:[0-9]{2}) ([+-][0-9]{4})\]

是否可以添加以下修改此表达式?

  1. 通过重新排序捕获的组将日期重新排序为 YYYY-MM-DD

  2. 将月份缩写更改为等效月份编号(4 月至 4 日)

需要进行这些更改才能使用日志中的日期/时间作为 SQL 时间戳列键的输入将 Fastly 日志导入 AWS Athena 数据库。

我已经在 Google 和 Stack Overflow 上进行了搜索,但只发现替换是一个单独的表达式。

任何帮助是极大的赞赏; 谢谢!

更新:这是我的 Athena Create Table 语句,其中我的正则表达式用于填充我的 Fastly 日志中的数据。

create external table if not exists logsdb.service_logs_2021_04_04
(
   `syslog_prefix`            string,
   `remote_ip_address`        string,
   `dashes`                   string,
   `timestamp`                timestamp,
   `url_request`              string,
   `final_status_code`        smallint,
   `response_size`            int,
   `fastly_datacenter`        string,
   `fastly_cache_state`       string,
   `client_ip_address`        string,
   `client_geo_location`      string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES
(
   'serialization.format' = '1',
   'input.regex' = '^(.+]:) ([0-9.]+) ("-" "-") \\[([0-9]{2})\/([A-Za-z]{3})\/([0-9]{4}):([0-9]{2}:[0-9]{2}:[0-9]{2}) ([+-][0-9]{4})\\] \"(.+?)\" ([0-9]{3}) ([0-9]+) ([A-Za-z]+) ([A-Za-z-]+) ([0-9.]+) ([A-Za-z ]+)$'
)
LOCATION 's3://weblog-query-source/service-logs/2021-04-04/'
TBLPROPERTIES ('has_encrypted_data'='false')

标签: mysqlsqlregexamazon-s3amazon-athena

解决方案


解决复杂正则表达式的一种简单方法是使用SELECT查询转换值。例如:

select date_format(date_parse('04/Apr/2021:12:21:24', '%d/%b/%Y:%T%'), '%Y-%m-%d')

将输出:2021-04-04


推荐阅读