Nikolai Konovalov
Nikolai Konovalov

Reputation: 21

Regex - extract ip

I'm tring to pull some data from a plain log file with a json convrestor. this is the log entry:

01/04/2022 15:29:34.2934 +03:00 - [INFO] - [w3wp/LPAPI-Last Casino/177] - AppsFlyerPostback?re_targeting_conversion_type=&is_retargeting=false&app_id=id624512118&platform=ios&event_type=in-app-event&attribution_type=organic&ip=8.8.8.8&name=blabla

This is the regex I'm using:

(?P<date>[0-9]{2}\/[0-9]{2}\/[0-9]{4}).(?P<time>\s*[0-9]{2}:[0-9]{2}:[0-9]{2}).*(?P<level>\[\D+\]).-.\[(?P<application_subsystem_thread>.*)\].-.(?P<message>.*)

This is the output I'm getting:

{
  "application_subsystem_thread": "w3wp/LPAPI-Last Casino/177",
  "date": "01/04/2022",
  "level": "[INFO]",
  "message": "AppsFlyerPostback?re_targeting_conversion_type=&is_retargeting=false&app_id=id624512118&platform=ios&event_type=in-app-event&attribution_type=organic&ip=8.8.8.8&name=blabla",
  "time": "15:29:34"
}

As you can see, the convertor is using the group names as the json key. I would like to get the following output instead:

{
  "application_subsystem_thread": "w3wp/LPAPI-Last Casino/177",
  "date": "01/04/2022",
  "level": "[INFO]",
  "message": "AppsFlyerPostback?re_targeting_conversion_type=&is_retargeting=false&app_id=id624512118&platform=ios&event_type=in-app-event&attribution_type=organic&ip=8.8.8.8&name=blabla",
  "time": "15:29:34",
  "ip": "8.8.8.8"
}

As you can see I would like to get the IP as well how can I do it ?

Upvotes: 2

Views: 82

Answers (1)

ug_
ug_

Reputation: 11440

You could extract it from the part of the message:

As defined in the message it could be captured with

ip\=(?P<ip_address>(?:[0-9]+\.){3}[0-9]+)

So then we incoperate it as part of the greater message group

(?P<message>.*ip\=(?P<ip_address>(?:[0-9]+\.){3}[0-9]+).*)

Resulting in the final expression

(?P<date>[0-9]{2}\/[0-9]{2}\/[0-9]{4}).(?P<time>\s*[0-9]{2}:[0-9]{2}:[0-9]{2}).*(?P<level>\[\D+\]).-.\[(?P<application_subsystem_thread>.*)\].-.(?P<message>.*ip\=(?P<ip_address>(?:[0-9]+\.){3}[0-9]+).*)

var message = `01/04/2022 15:29:34.2934 +03:00 - [INFO] - [w3wp/LPAPI-Last Casino/177] - AppsFlyerPostback?re_targeting_conversion_type=&is_retargeting=false&app_id=id624512118&platform=ios&event_type=in-app-event&attribution_type=organic&ip=8.8.8.8&name=blabla`;

// NOTE - The regex in this code sample has been modified to be ECMAScript compliant
console.log(/(?<date>[0-9]{2}\/[0-9]{2}\/[0-9]{4}).(?<time>\s*[0-9]{2}:[0-9]{2}:[0-9]{2}).*(?<level>\[\D+\]).-.\[(?<application_subsystem_thread>.*)\].-.(?<message>.*ip\=(?<ip_address>(?:[0-9]+\.){3}[0-9]+).*)/gm.exec(message).groups)

Upvotes: 1

Related Questions