I have a hard time figuring out if this is possible with regexes. I have the following string (The original string is longer, it is a json string):
... "WorkstationName":"WS-8300E-007","IpAddress":"192.10.10.10" ...
And I want to catch the IpAddress or, if the IpAddress does not exists, the WorkstationName
# IPADDR = 192.10.10.10
... "WorkstationName":"WS-8300E-007","IpAddress":"192.10.10.10" ...
# IPADDR = WS-8300E-007
... "WorkstationName":"WS-8300E-007","IpAddress":"-" ...
I have tried several patterns:
but without success, I need to capture the pattern in a named group (?P<ipaddr>) so that the output can be processed by other software.
The latest regex I ended up with is :
(?:("WorkstationName":)(?=.*IpAddress":"-"))?(?(1)(?:"([^"]+)")?|.*IpAddress":"([^"]+")?)(?P<ipaddr>(?(2)\2|\3))
So, basically, I do:
The hard time I'm having is using the named group, I have already suceeded in capturing everything in 2 groups, but I absolutely need to be on the same group depending on the string.
I cannot use JSON parsers
This one should suit your needs:
^.*(?:IpAddress(?!":"-)|WorkstationName)":"(?P<ipaddr>[^"]+)

Visualization by Debuggex
Demo on regex101
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With