gpt4 book ai didi

regex - golang 删除数组的一个维度

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:22 27 4
gpt4 key购买 nike

我在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 函数或其他......的 slice

谢谢

最佳答案

这更像是 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 库没有必要为您提供完全符合您描述的功能,因为这些函数的用途非常有限。

编写这样的代码片段或函数也是微不足道的任务,因此您必须根据您非常特殊的需求组合和匹配您自己的代码或函数。

关于regex - golang 删除数组的一个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com