我很难弄清楚这是否可以用正则表达式实现。我有以下字符串(原始字符串更长,它是一个 json 字符串):
... "WorkstationName":"WS-8300E-007","IpAddress":"192.10.10.10" ...
Run Code Online (Sandbox Code Playgroud)
我想捕获IpAddress或者,如果 IpAddress 不存在,则WorkstationName
# IPADDR = 192.10.10.10
... "WorkstationName":"WS-8300E-007","IpAddress":"192.10.10.10" ...
# IPADDR = WS-8300E-007
... "WorkstationName":"WS-8300E-007","IpAddress":"-" ...
Run Code Online (Sandbox Code Playgroud)
我尝试了几种模式:
但没有成功,我需要在命名组中捕获模式,(?P<ipaddr>)以便其他软件可以处理输出。
我最终得到的最新正则表达式是:
(?:("WorkstationName":)(?=.*IpAddress":"-"))?(?(1)(?:"([^"]+)")?|.*IpAddress":"([^"]+")?)(?P<ipaddr>(?(2)\2|\3))
Run Code Online (Sandbox Code Playgroud)
所以,基本上,我这样做:
我遇到的困难是使用命名组,我已经成功捕获了 2 组中的所有内容,但我绝对需要根据字符串在同一组中。
我不能使用 JSON 解析器
这个应该适合您的需求:
^.*(?:IpAddress(?!":"-)|WorkstationName)":"(?P<ipaddr>[^"]+)
Run Code Online (Sandbox Code Playgroud)

Debuggex可视化