卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35598本站已运行397

python 正则表达式 split 函数在 golang 中等效

python 正则表达式 split 函数在 golang 中等效

在编程领域中,正则表达式是一种强大的工具,用于匹配和处理字符串。在Python中,split函数是一个常用的正则表达式函数,用于将字符串分割成子字符串。然而,对于使用Golang的开发者来说,他们可能想知道在Golang中如何实现与Python中split函数相同的功能。在本文中,php小编子墨将向您介绍如何在Golang中等效地使用正则表达式split函数,以便更好地利用这个功能强大的工具。

问题内容

我有下面的 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 的帮助下解决问题,你最终会遇到两个问题!!!

卓越飞翔博客
上一篇: 修改go以使用Gem5 m5ops:go tool dist显示导入消息然后退出
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏