英文:
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
<none>
USB Device Filters:
Name: Server2 10.0.0.12
Groups: /
Guest OS: Debian (64-bit)
\n
<none>
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:)
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:
If you don't want to capture Name:\s
you can do:
^Name:\s*(.*?)USB Device Filters:
You don't need to escape the spaces with (?=USB\ Device\ Filters:)
in either language. All have (?ms)
flags set.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论