python regex拆分函数等价于golang



我有下面的python代码来匹配regex::

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   ? 
]

我认为regex是语言相关的,所以在python中使用的split()函数不会对golang有帮助。使用了regexp包中的多个Find*()函数,但没有找到一个可以提供上述python程序的输出。

输出字符串数组的目的是分隔不能转换为float&如果字符串可以解析为浮点数,则计算移动平均线。

最后,我把所有的&显示类似Linuxwatch命令的输出

你需要更多的细节/背景吗?我很乐意分享。

非常感谢你的帮助!

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

我使用了Split&FindAllString函数获得所需输出。

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

为了匹配给定的输出,请看看这是否对您有帮助。

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)

最新更新