将一个Python的前瞻断言正则表达式转换为有效的Golang代码。

huangapple go评论85阅读模式
英文:

Converting a python lookahead assertion regex to valid Golang

问题

我有以下在Python中运行良好的正则表达式(由于前瞻断言)。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	myinput := `Name:            Server1 10.0.0.11
Groups:          /
Guest OS:        Ubuntu (64-bit)
\n
<none>
USB Device Filters:

Name:            Server2 10.0.0.12
Groups:          /
Guest OS:        Debian (64-bit)
\n
<none>
USB Device Filters:`

	re := regexp.MustCompile(`(?m)^(?=Name:)(.*?)(?=USB\ Device\ Filters:)`)
	matches := re.FindAllStringSubmatch(myinput, -1)

	for _, match := range matches {
		fmt.Println(match[1])
	}
}

请注意,Golang的正则表达式语法与Python的略有不同。在上面的示例中,我使用了regexp包来编译和匹配正则表达式。(?m)是一个标志,用于启用多行模式,使^$匹配每一行的开头和结尾。FindAllStringSubmatch函数返回一个切片,其中包含所有匹配的组。在这个例子中,我们只关心第一个组,因此我们打印出了match[1]

希望这可以帮助到你!

英文:

I have the following regex that works well in Python (due to lookahead assertions).

some_list = re.findall('^(?=Name:)(.*?)(?=USB\ Device\ Filters:)', myinput, re.MULTILINE|re.DOTALL)

See example of myinput in the code block below.

Name: will always be the beginning of a group and USB Device Filters: will always be the end of a group. Not all lines have a valid key:value, e.g., can have <none> or a blank line.

Name:            Server1 10.0.0.11
Groups:          /
Guest OS:        Ubuntu (64-bit)
\n
&lt;none&gt;
USB Device Filters:

Name:            Server2 10.0.0.12
Groups:          /
Guest OS:        Debian (64-bit)
\n
&lt;none&gt;
USB Device Filters:

Can anyone help me convert this into a valid Golang regex?

The ultimate goal is to parse myinput and get a slice of matched groups.

答案1

得分: 2

在Python中给出以下正则表达式:

^(?=Name:)(.*?)(?=USB Device Filters:)

演示

由于^(?=Name:)是一个零宽断言,Name: 被后面的捕获组捕获。

在Golang中,你可以使用以下正则表达式来捕获相同的内容:

^(Name:.*?)USB Device Filters:

演示

如果你不想捕获Name:\s,你可以使用以下正则表达式:

^Name:\s*(.*?)USB Device Filters:

演示

在任何一种语言中,你都不需要使用(?=USB\ Device\ Filters:)来转义空格。所有的正则表达式都设置了(?ms)标志。

英文:

Given this in Python:

^(?=Name:)(.*?)(?=USB Device Filters:)

Demo

Since ^(?=Name:) is a zero width assertion, Name: is captured by the capturing groups following it.

You can capture the same in Golang with this:

^(Name:.*?)USB Device Filters:

Demo

If you don't want to capture Name:\s you can do:

^Name:\s*(.*?)USB Device Filters:

Demo

You don't need to escape the spaces with (?=USB\ Device\ Filters:) in either language. All have (?ms) flags set.

huangapple
  • 本文由 发表于 2017年3月24日 10:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/42990442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定