vendredi 20 février 2015

How to avoid different capture group numbers in a regex?

I'm trying to capture an IP address in a log and revert on a hostname if the address is 0.0.0.0.


Here are some examples of logs:



Foo bar ip=0.0.0.0 baz host=YOLO-PC foobar bazinga



In this case, I want "YOLO-PC" because IP is 0.0.0.0



Foo bar ip=12.23.34.45 baz host=FOOBAR-PC foobar bazinga



In this case, I want "12.23.34.45".


Here's what I tried:



ip=(?:0\.0\.0\.0|(\d+\.\d+\.\d+\.\d+)).*?host=(?(1).|(\S+))


It works, but when IP is 0.0.0.0, it creates a second group and the program behind it can't fetch group #2, only group #1.


How can I do this? Put it all in only one group? Is there a better solution?


Aucun commentaire:

Enregistrer un commentaire