首頁  >  文章  >  後端開發  >  python 正規表示式 split 函數在 golang 中等效

python 正規表示式 split 函數在 golang 中等效

王林
王林轉載
2024-02-13 19:45:09421瀏覽

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 的幫助下解決問題,你最終會遇到兩個問題! ! !

以上是python 正規表示式 split 函數在 golang 中等效的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除