KDB字符串解析提取日期:适配多种日期条件格式的方法
在KDB中解析查询日志字符串列提取日期的通用方案
问题场景
需要解析KDB表中存储用户查询日志的字符串列,提取其中与date关键字关联的日期,转为KDB日期格式存入新列。示例查询字符串包括:
"select from table where date=2023.01.01" "select from table2 where date = 2024.01.01" "select from table3 where date >= 2022.01.01" "select from table4 where date>=2021.01.01" "select from table5 where date within (2020.01.01;2020.12.31)"
当前使用的方法仅适配date=格式:
update queryDate:first each "," vs/: last each "date=" vs/: colName from tableName; update "D"$queryDate from tableName;
无法处理带空格的运算符、无空格复合运算符以及date within等场景。
解决方案
利用KDB的正则表达式函数re.find实现灵活匹配,覆盖所有目标场景:
方法1:精准匹配date关联的单日期
针对date后接=/>=/<=/>/<(含有无空格)的场景,直接提取关联日期:
update queryDate:"D"$first each re.find["date\\s*[<>]=?\\s*(\\d{4}\\.\\d{2}\\.\\d{2})"; colName; 1] from tableName;
- 正则说明:
date\\s*匹配date关键字及后续任意空格[<>]=?覆盖所有常见比较运算符(=/>=/<=/>/<)(\\d{4}\\.\\d{2}\\.\\d{2})捕获yyyy.mm.dd格式的日期字符串- 第三个参数
1指定返回正则捕获组的内容(仅提取日期部分)
方法2:适配date within场景
如需提取within后的日期(示例取第一个日期,可按需调整为第二个):
update queryDate:"D"$first each re.find["date\\s*within\\s*\\((\\d{4}\\.\\d{2}\\.\\d{2})"; colName; 1] from tableName;
合并处理所有场景
通过合并正则匹配结果,自动适配所有目标场景:
update queryDate:{"D"$first where not null x} each ( // 先匹配单日期运算符场景 re.find["date\\s*[<>]=?\\s*(\\d{4}\\.\\d{2}\\.\\d{2})"; colName; 1], // 再匹配within场景 re.find["date\\s*within\\s*\\((\\d{4}\\.\\d{2}\\.\\d{2})"; colName; 1] ) from tableName;
该逻辑会优先取单日期场景的匹配结果,若无则取within场景的第一个日期,确保所有情况都能覆盖。
验证
将上述代码应用到包含所有测试场景的表中,即可成功提取所有date关联的日期并转为KDB原生日期类型。
内容的提问来源于stack exchange,提问作者CleanSock
相关产品推荐
相关产品推荐

