繁体   English   中英

如何使用 REGEXP_EXTRACT 根据中间字符将字符串分成两部分?

[英]How can I split a string into two based on a character inbetween using REGEXP_EXTRACT?

我需要根据一个字符将一个字符串分成两个,我需要在不使用SPLIT命令的情况下执行此操作。

我拥有的:

细绳
水果=橙子
水果=苹果
蔬菜=洋葱

我需要的:

splitstring1 拆分字符串2
水果 橘子
水果 苹果
蔬菜 洋葱

我怎样才能用REGEXP_EXTRACT解决这个问题?

根据您的要求考虑以下查询:

SELECT
  REGEXP_EXTRACT(string, r'^[a-zA-Z]+') AS splitstring1,
  REGEXP_EXTRACT(string, r'[a-zA-Z]+$') AS splitstring2
FROM
  `project.dataset.table`;

结果:

在此处输入图像描述

编辑:根据您的新要求:

  • 样本输入: fruit=apples and oranges

  • 预期为 Output:一列为"fruit" in one column and "apples and oranges" in another column

考虑以下查询:

SELECT
  REGEXP_EXTRACT(string, r'^[a-zA-Z0-9 ]+') AS splitstring1,
  REGEXP_EXTRACT(string, r'[a-zA-Z0-9 ]+$') AS splitstring2
FROM
  `project.dataset.table`;

结果:

在此处输入图像描述

考虑以下方法

select 
  arr[offset(0)] as splitstring1,
  arr[safe_offset(1)] as splitstring2
from  your_table,
unnest([struct(regexp_extract_all(string, r'[^=]+') as arr)])          

如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM