【问题标题】:Using REGEX_EXTRACT to pull one value but not the other from duplicates使用 REGEX_EXTRACT 从重复项中提取一个值而不是另一个值
【发布时间】:2019-11-14 22:55:57
【问题描述】:

我在从大型文本日志中提取特定变量时遇到问题。

正常的日志是这样的:

 metadata {
    unique_id: "88dvsq113-0dcf-410f-84fb-d342076def6f"
    webhook_response_time: 155
    intent_name: "Dogs are the best"
    variable_one: "true"
    variable_two: "false"
    variable_three: "false"
  }

我只是想拉intent_name变量,所以我使用正则表达式:

SELECT REGEXP_EXTRACT(textPayload, r"intent_name:(.+)") AS intent_name FROM table1

只提取“狗是最好的”的价值。现在,在日志中,有两个不同的部分包含短语“intent_name”,所以这个正则表达式不会拉到我需要的地方。以下是新日志的示例:

  metadata {
    intent_id: "a664f00f-8105-4e09-bc34-2836dbe89ee1"
    webhook_response_time: 105
    intent_name: "Dogs are the best"
    execution_sequence {
      intent_id: "e231c181-31d9-4bfa-b2d8-7a52314bc628"
      intent_name: "Cats are the best"
      variable_one: "true"
      variable_two: "false"
      variable_three: "false"
    }

如何编写一个表达式来仅提取第一个 intent_name 值“Dogs are the best”而不是不在 execution_sequence 括号内的那个?

【问题讨论】:

  • 是mysql还是postgresql?不清楚。为什么不只是json_extract(json_data, '$.intent_name')data::json->'intent_name'?方式更简单,更不容易出错,更清洁,更易于维护;到处都是赢家。
  • 我从中提取的表实际上不是 json,它是直接从我不再有权访问的 JSON 文件中导入的文本格式。这实际上是在 googleSQL 中(几乎与 postgre 相同),但没有标签!
  • @TomUpdike:google-bigquery 有一个标签,这就是你所说的 google SQL。
  • @GMB 我没看到,改了。感谢您帮助 stackoverflow 新手!
  • 正则表达式对于解析这样的结构化嵌套数据非常不利,尤其是当嵌套可以深入到任意级别时。换句话说,如果您的策略是跟踪左括号(或括号、引号等)并将它们与右括号匹配以确定某些内容是否应该匹配,那么您可能会遇到麻烦。但是,如果 indentation 是一致的,则可以将其用作锚点。类似r"^ {4}intent_name:(.+)"

标签: sql regex google-bigquery


【解决方案1】:

JSON 值会容易得多。但是对于第二种日志格式,您可以这样做:

select regexp_extract(textPayload, r"""intent_name: ("[^"]+")[\s\S]*execution_sequence""")
from (select '''metadata {
    unique_id: "88dvsq113-0dcf-410f-84fb-d342076def6f"
    webhook_response_time: 155
    intent_name: "Dogs are the best"
    variable_one: "true"
    variable_two: "false"
    variable_three: "false"
  }''' as textPayload union all
      SELECT '''metadata {
    intent_id: "a664f00f-8105-4e09-bc34-2836dbe89ee1"
    webhook_response_time: 105
    intent_name: "Dogs are the best"
    execution_sequence {
      intent_id: "e231c181-31d9-4bfa-b2d8-7a52314bc628"
      intent_name: "Cats are the best"
      variable_one: "true"
      variable_two: "false"
      variable_three: "false"
    }'''
     ) x

这不适用于第一种格式,但如果您需要同时支持这两种格式,您可以使用 case 表达式。

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2023-02-04
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多