【问题标题】:Second substring in Google Big QueryGoogle Big Query 中的第二个子字符串
【发布时间】:2016-04-21 14:24:48
【问题描述】:

我正在尝试使用 Google Big Query 查找字符串中子字符串第二次出现的索引。

例如,在字符串 'challcha' 中,'ch' 第二次出现在位置 6。

我知道这可以在 Oracle 中使用 CharIndex 来实现。我正在尝试在 Google Big Query 中实现这一目标。

感谢任何帮助!

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    对于带有纯 SQL String functions 的 BigQuery

    SELECT test, 
      INSTR(test, 'ch') + 1 + INSTR(SUBSTR(test, INSTR(test, 'ch') + 2), 'ch') AS pos,
    FROM 
      (SELECT 'challcha' AS test),
      (SELECT 'chcha' AS test),
      (SELECT 'chha' AS test)
    WHERE 
      INSTR(SUBSTR(test, INSTR(test, 'ch') + 2), 'ch') > 0
    

    注意:INSTR 是区分大小写的,所以如果您有混合大小写,您可能希望将所有内容放在 LOWER 或 UPPER 中

    BigQuery User-Defined Functions

    SELECT test, pos FROM JS(
    (
      SELECT test FROM 
        (SELECT 'challcha' AS test),
        (SELECT 'chcha' AS test),
        (SELECT 'chha' AS test)
    ) ,
    test,
    "[{name: 'test', type:'string'},
      {name: 'pos', type:'integer'}
      ]
    ",
    "function(r, emit) {
      var search = 'ch';
      var pos1 = r.test.indexOf(search) + 1;
      var pos2 = r.test.indexOf(search, pos1) + 1;
      if (pos1 * pos2 == 0) pos2 = 0
      emit({test: r.test, pos: pos2});
    }"
    )
    

    使用纯 BigQuery Regular expression functions

    SELECT test, 
      LENGTH(REGEXP_EXTRACT(test, r'(?i)(.*?)ch')) + 3 + 
        LENGTH(REGEXP_EXTRACT(REGEXP_EXTRACT(test, r'(?i)ch(.*)'), r'(?i)(.*?)ch')) AS len,
    FROM 
      (SELECT 'ChallCha' AS test),
      (SELECT 'abChallCha' AS test),
      (SELECT 'chcha' AS test),
      (SELECT 'chha' AS test)
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2020-02-14
      • 1970-01-01
      • 2020-06-19
      • 2018-04-23
      • 2013-12-17
      • 2021-12-19
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多