search
HomeBackend DevelopmentGolangpython regular expression split function equivalent in golang

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

In the field of programming, regular expressions are a powerful tool for matching and processing strings. In Python, the split function is a commonly used regular expression function used to split a string into substrings. However, for developers using Golang, they may wonder how to achieve the same functionality in Golang as the split function in Python. In this article, PHP editor Zimo will introduce you to how to use the regular expression split function equivalently in Golang to better utilize this powerful tool.

Question content

I have the following python code to match a regular expression::

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

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

print(p)

It gives this output:: ['', '', 'h', 'e', ​​'', '', 'l', '', 'l', '', 'o', '', ',', ' ', ' ', '', 'w', '', 'h', 'e', ​​'', '', 'r', 'e', ​​'', '', ' ', '', ' a' , '', 'r', 'e', ​​'', '', ' ', '', 'y', '', 'o', '', 'u', '', ' ', '1.1 ', '', '', '?', '', '']

I'm trying to get the above output using 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)

}

I get the following output::

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

I think regular expressions are language dependent, so the split() function used in python is not helpful for golang. Used multiple find*() functions from the regexp package, but could not find one that would provide the output of the above python program.

The goal of the output string array is to separate characters that cannot be converted to float, and if the string can be parsed as a float, I calculate the moving average.

Finally, I combine everything and present the output like a linux watch command.

Do you need more details/background? I'm happy to share.

Thank you for your help!

Workaround

In the meantime, I got something that works for my use case. It is not exactly the same format as python but does not have the empty string/character.

I used the split and findallstring functions to get the desired 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])
    }

With the above code snippet, I get something like ::

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

I'm not very good at regex, and somehow the above method works for my use case.

On a lighter note, I've heard colleagues joke that if you solve a problem with the help of regex, you'll end up with two problems! ! !

The above is the detailed content of python regular expression split function equivalent in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
java怎么对字符串排序java怎么对字符串排序Apr 02, 2024 am 02:18 AM

Java 中对字符串排序的方法:使用 Arrays.sort() 方法对字符串数组按升序排序。使用 Collections.sort() 方法对字符串列表按升序排序。使用 Comparator 接口对字符串进行自定义排序。

\0在c语言中是什么意思\0在c语言中是什么意思Apr 27, 2024 pm 10:54 PM

C 语言中,\0 是字符串的结束标志,称为空字符或终止符。由于字符串在内存中以字节数组形式存储,编译器通过 \0 识别字符串结束,确保正确处理字符串。\0 工作原理:编译器遇到 \0 时停止读取字符,之后的字符被忽略。\0 自身不占存储空间。好处包括可靠的字符串处理、提高效率(无需扫描整个数组查找结束)以及方便比较和操作。

args在java中是什么意思args在java中是什么意思Apr 25, 2024 pm 10:15 PM

args 在 Java 中表示命令行参数,是一个字符串数组,包含程序启动时传递给它的参数列表。它仅在 main 方法中可用,其默认值为一个空数组,通过索引可以访问每个参数。args 用于接收和处理命令行参数,从而在程序启动时进行配置或提供输入数据。

在C语言环境下如何对中文字符进行排序?在C语言环境下如何对中文字符进行排序?Feb 18, 2024 pm 02:10 PM

如何在C语言编程软件中实现中文字符排序功能?在现代社会,中文字符排序功能在很多软件中都是必不可少的功能之一。无论是在文字处理软件、搜索引擎还是数据库系统中,都需要对中文字符进行排序,以便更好地展示和处理中文文本数据。而在C语言编程中,如何实现中文字符排序功能呢?下面将简要介绍一种方法。首先,为了在C语言中实现中文字符排序功能,我们需要使用到字符串比较函数。然

C++ 函数对程序性能有哪些影响?C++ 函数对程序性能有哪些影响?Apr 12, 2024 am 09:39 AM

函数对C++程序性能的影响包括函数调用开销、局部变量和对象分配开销:函数调用开销:包括堆栈帧分配、参数传递和控制权转移,对小函数影响显著。局部变量和对象分配开销:大量局部变量或对象创建和销毁会导致堆栈溢出和性能下降。

C语言程序的启动点是哪里?C语言程序的启动点是哪里?Feb 20, 2024 pm 12:12 PM

C语言程序的运行起点是什么?C语言作为一种高级编程语言,是一种十分常用的编程语言之一。在学习C语言的过程中,很多人都会对C程序的运行起点感到困惑。那么,C语言程序的运行起点到底是什么呢?答案是main函数。在C语言程序中,程序的执行都是从main函数的开始处开始的。main函数是C语言程序的入口点,也是程序员定义的第一个被执行的函数。它的主要作用是用来定义程

如何在 Golang 中用匿名数组反序列化 json?如何在 Golang 中用匿名数组反序列化 json?Feb 14, 2024 am 11:24 AM

我从外部服务器接收此json:[["010117"、"070117"、"080117"]、["080117"、"140117"、"150117"]、["150117"、"210117"、"220117"]]我需要解析它packagemainimport("encoding/json""fmt""io""os""runtime")typeRangestruct{FromstringTostring

探索 PHP 数组去重算法的复杂度探索 PHP 数组去重算法的复杂度Apr 28, 2024 pm 05:54 PM

PHP数组去重算法的复杂度:array_unique():O(n)array_flip()+array_keys():O(n)foreach循环:O(n^2)

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!