登录
首页 >  Golang >  Go问答

如何在 golang 中使用正则表达式的 split 函数

来源:stackoverflow

时间:2024-02-17 17:03:22 459浏览 收藏

本篇文章给大家分享《如何在 golang 中使用正则表达式的 split 函数》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我有下面的 python 代码来匹配正则表达式::

import re
digits_re = re.compile("([0-9ee.+]*)")

p = digits_re.split("hello, where are you 1.1?")

print(p)

它给出了这个输出:: ['', '', 'h', 'e', '', '', 'l', '', 'l', '', 'o', '', ',', '', ' '、''、'w'、''、'h'、'e'、''、''、'r'、'e'、''、''、' '、''、'a' , '', 'r', 'e', '', '', ' ', '', 'y', '', 'o', '', 'u', '', ' ', '1.1 ', '', '', '?', '', '']

我正在尝试使用 golang 获得上述输出。

package main

import (
    "bytes"
    "fmt"
    "log"
    "os/exec"
    "regexp"
    "strconv"
)

func main() {
    // execute the command and get the output
    cmd := exec.command("echo", "hello, where are you 1.1?")
    var out bytes.buffer
    cmd.stdout = &out
    err := cmd.run()
    if err != nil {
        log.fatal(err)
    }

    // extract the numerical values from the output using a regular expression
    re := regexp.mustcompile(`([0-9ee.+]*)`)
    //matches := re.findallstring(out.string(), -1)
    splits := re.split(out.string(), -1)
    fmt.println(splits)

}

我得到如下输出::

[H l l o ,   w h r   a r   y o u   ? 
]

我认为正则表达式与语言相关,因此 python 中使用的 split() 函数对 golang 没有帮助。使用了 regexp 包中的多个 find*() 函数,但找不到可以提供上述 python 程序输出的函数。

输出字符串数组的目标是分隔无法转换为 float 的字符,如果字符串可以解析为浮点数,我会计算移动平均值。

最后,我将所有内容结合起来并呈现输出,如 linux watch 命令。

您需要更多详细信息/背景吗?我很乐意分享。

非常感谢您的帮助!


正确答案


与此同时,我得到了一些适合我的用例的东西。它与 python 的格式不完全相同,但没有空字符串/字符。

我使用 splitfindallstring 函数来获得所需的输出。

// unfortunately go regex split doesn't work like python
    // so we construct the entire array with matched string (numericals)
    // and the split strings to combine the output
    splits := digitsre.split(string(out), -1)
    matches := digitsre.findallstring(string(out), -1)

    p := []string{}
    for i := 0; i < len(splits); i++ {
        p = append(p, matches[i])
        p = append(p, splits[i])
    }

通过上面的代码片段,我得到类似 ::

[H e l l o ,   w h e r e   a r e   y o u  1.1 ?]

我不太擅长 regex,不知何故,上面的方法适合我的用例。

说得轻松一点,我听到同事开玩笑说,如果你在 regex 的帮助下解决问题,你最终会遇到两个问题!!!

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>