簡體   English   中英

用於獲取文件路徑直到給定斜杠數字的正則表達式

[英]Regexp expression for getting the file path till a given slash number

我有一個日志表,其中一行 'path' 的值類似於root/home/desktop/parent/child/grandchild我想根據一些 integer 輸入 'n' 在此行上進行分組,其中 n 是直到斜線的數量我們要提取 substring 然后對其進行分組。 例如:在這種情況下,如果 n = 1 如果 n 為 3,我想按 'root/' 分組,如果想按 'root/home/desktop/' 分組。 我怎樣才能在 BigQuery 中實現這一點? 我可以使用相同的正則表達式還是有更好的方法來實現這一點? 無論采用何種方法,都希望能給出一些解釋。 謝謝!!

不確定下面的例子是否真的需要任何額外的解釋

select *, 
  split(path, '/')[safe_offset(0)],
  split(path, '/')[safe_offset(1)],
  split(path, '/')[safe_offset(2)],
  split(path, '/')[safe_offset(3)],
  split(path, '/')[safe_offset(4)],
  split(path, '/')[safe_offset(5)]
from your_table    

與 output

在此處輸入圖像描述

我想以字符串的形式組合拆分,直到最后一個斜杠......

從頭開始獲取部分路徑 - 使用下面的示例

create temp function get_path(path string, n int64) as ((
  select string_agg(part, '/' order by offset)
  from unnest(split(path, '/')) part with offset
  where offset < n
));
select  
  get_path(path, 1) n1,
  get_path(path, 2) n2,
  get_path(path, 3) n3,
  get_path(path, 4) n4,
  get_path(path, 5) n5,
  get_path(path, 6) n6
from your_table

output 如下所示

在此處輸入圖像描述

如果您想使用正則表達式 - 請考慮以下內容

create temp function get_path(path string, n int64) as ((
  regexp_extract(path, r'(^(?:[^/]+/?){' || n || '})')
));
with your_table as (
  select 'root/home/desktop/parent/child/grandchild' path
)
select  
  get_path(path, 1) n1,
  get_path(path, 2) n2,
  get_path(path, 3) n3,
  get_path(path, 4) n4,
  get_path(path, 5) n5,
  get_path(path, 6) n6,
from your_table    

與 output

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM