簡體   English   中英

golang刪除數組的維數

[英]golang drop a dimension of array

我在golang中有這樣的代碼

func GetIndexes(body string) ([]int, error) {

    indexPattern, err := regexp.Compile(`<div class="post article" id="([0-9]+)">`)
    res := indexPattern.FindAllStringSubmatch(body, -1)

    fmt.Printf("%v\n", res)

    //Just for debug
    return make([]int, 5), err
}

例如結果是:

[ 
[<div class="post article" id="55987"> 55987] 
[<div class="post article" id="6717024"> 6717024] 
[<div class="post article" id="6440542"> 6440542] 
[<div class="post article" id="6800745"> 6800745] 
[<div class="post article" id="449954"> 449954] 
[<div class="post article" id="427586"> 427586] 
[<div class="post article" id="5418445"> 5418445] 
[<div class="post article" id="559225"> 559225]
... 
]

我正在尋找一種方法來獲得像

[55987, 6717024, 6717024, ...] 

我可以對要查找的數組和副本值進行調整,但是我不確定這是更好的方法。 這就是為什么我問自己是否可以刪除此數組的列,或者為什么不使用lambdas函數或其他函數創建某種切片的原因...

謝謝

這更多是RegEx引擎問題,因為引擎將以以下格式輸出結果:

res[0] // will be the first matched "whole string" occurrence
res[0][0] // will be the whole string match
res[0][1] // will be the first grouped match -- the things in parenthesis
res[0]['some_name'] // will be a named group match

您要做的是遍歷res[i]並檢索res[i][1]

由於您要匹配的RegEx可能非常復雜-它可能具有許多分組匹配,許多命名分組匹配等-結果變量也可能相當復雜。

由於結果變量的(可能的)復雜性,RegEx庫沒有必要向您提供與您描述的功能完全相同的功能,因為這些功能的用途非常有限。

同樣,編寫這樣的代碼段或函數段也是微不足道的任務,因此您必須根據非常特殊的需求組合和匹配自己的代碼。

暫無
暫無

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

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