在编程领域中,正则表达式是一种强大的工具,用于匹配和处理字符串。在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()
函数对 split()
函数对 golang
没有帮助。使用了 regexp
包中的多个 find*()
没有帮助。使用了 regexp
包中的多个 find*()
函数,但找不到可以提供上述 python 程序输出的函数。
输出字符串数组的目标是分隔无法转换为 float
的字符,如果字符串可以解析为浮点数,我会计算移动平均值。
最后,我将所有内容结合起来并呈现输出,如 linux watch
命令。
您需要更多详细信息/背景吗?我很乐意分享。
非常感谢您的帮助!
解决方法
与此同时,我得到了一些适合我的用例的东西。它与 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
的帮助下解决问题,你最终会遇到两个问题!!!
以上是python 正则表达式 split 函数在 golang 中等效的详细内容。更多信息请关注PHP中文网其他相关文章!

在Go编程中,有效管理错误的方法包括:1)使用错误值而非异常,2)采用错误包装技术,3)定义自定义错误类型,4)复用错误值以提高性能,5)谨慎使用panic和recover,6)确保错误消息清晰且一致,7)记录错误处理策略,8)将错误视为一等公民,9)使用错误通道处理异步错误。这些做法和模式有助于编写更健壮、可维护和高效的代码。

在Go中实现并发可以通过使用goroutines和channels来实现。1)使用goroutines来并行执行任务,如示例中同时享受音乐和观察朋友。2)通过channels在goroutines之间安全传递数据,如生产者和消费者模式。3)避免过度使用goroutines和死锁,合理设计系统以优化并发程序。

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

go'serrorhandlingisexplicit,治疗eRROSASRETRATERTHANEXCEPTIONS,与pythonandjava.1)go'sapphifeensuresererrawaresserrorawarenessbutcanleadtoverbosecode.2)pythonandjavauseexeexceptionseforforforforforcleanerCodebutmaymobisserrors.3)

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3汉化版
中文版,非常好用

Dreamweaver CS6
视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。