Google Big Query 中的第二个子字符串

Posted

技术标签:

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

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

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

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

感谢任何帮助!

【问题讨论】:

【参考方案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)

【讨论】:

以上是关于Google Big Query 中的第二个子字符串的主要内容,如果未能解决你的问题,请参考以下文章