Regex - Match only if substring exists

53 Views Asked by At

I'm struggling with a Regex for usage in Fail2Ban.

This is a line of logs I need to crawl:

Jul 14 13:30:44 servername kernel: [  803.539059] [UFW BLOCK] IN=eth0 OUT= MAC=somemacadress SRC=somesourceip DST=somedestinationip LEN=60 TOS=0x00 PREC=0x00 TTL=53 ID=18692 DF PROTO=TCP SPT=50852 DPT=5003 WINDOW=14600 RES=0x00 SYN URGP=0

I need the IP somesourceip which I am able to get with SRC=?(?P<host>\S+)

But: I only want it, if DPT=5003 is also present. This is the part where I am struggling.

Can somebody help?

Thanks a lot!

I've found ^.*substring.*$ to search for substrings, but I don't manage to combine both.

1

There are 1 best solutions below

1
James Thorpe On

You can use a positive lookahead:

SRC=?(?P<host>\S+).*(?=DPT=5003)

This matches your existing one, followed by zero or more other characters, followed by the DPT=5003 string.