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

将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.

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

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接