Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing either one or other group with regex

Tags:

regex

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:

  • conditional lookahead
  • capturing a backreference
  • other tries I forgot

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:

  • check if "WorkstationName" is followed, at some point by an invalid ip ("-")
  • if it is, capture the workstation name in \1
  • if the group \1 exists, capture the workstation name
  • otherwise capture the ip address

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

like image 631
kitensei Avatar asked Dec 02 '25 20:12

kitensei


1 Answers

This one should suit your needs:

^.*(?:IpAddress(?!":"-)|WorkstationName)":"(?P<ipaddr>[^"]+)

Regular expression visualization

Visualization by Debuggex

Demo on regex101

like image 61
sp00m Avatar answered Dec 04 '25 15:12

sp00m