doutuoji8418 2017-03-24 02:36
浏览 72
已采纳

将python前瞻断言正则表达式转换为有效的Golang

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 or a blank line.

Name:            Server1 10.0.0.11
Groups:          /
Guest OS:        Ubuntu (64-bit)


<none>
USB Device Filters:

Name:            Server2 10.0.0.12
Groups:          /
Guest OS:        Debian (64-bit)


<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条回答 默认 最新

  • duancheng1955 2017-03-24 02:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?