繁体   English   中英

python 正则表达式拆分 function 在 golang 中等效

[英]python regex split function equivalent in golang

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

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

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

print(p)

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

我正在尝试使用 golang 获取上述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)

}

我得到如下所示的 output::

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

我认为正则表达式依赖于语言,所以 python 中使用的split() function 对golang没有帮助。 使用了正则regexp package 的多个Find*()函数的一部分,但找不到可以提供上述 python 程序的 output 的函数。

output 字符串数组的目标是分隔不能转换为float的字符&如果一个字符串可以解析为浮点数,我计算移动平均值。

最后,我结合所有内容并呈现 output 就像 Linux watch命令。

您需要更多详细信息/上下文吗? 我很乐意分享。

非常感谢您的帮助!

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

我同时使用了SplitFindAllString函数来获得所需的 output。

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

要匹配给定的 output,请查看是否对您有帮助。

import re
p = re.sub(r"[0-9eE.+]", "", "Hello, where are you 1.1?")
p = [p] 
# p = list(p) ## based on your requirement
print(p)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM