Home > Mobile >  Regex - Match username inside Brackets and prepend string
Regex - Match username inside Brackets and prepend string

Time:03-26

I've a syslog message like this:

03-25-2022  18:02:51    Local1.Notice   192.168.1.1 Mar 25 18:02:51 2022 192.168.1.1 stm[6358]: <501199> <NOTI> AP:AP01 <192.168.1.1 aa:bb:cc:dd:ee>  User authenticated, mac-aa:bb:cc:dd:ee, username-my.username, IP-192.168.250.100, method-802.1x, role-blahblah

My first goal is: everytime that the line contains "User authenticated", extract the string that comes after username- (in this case: my.username) and prepend a string.

Wanted Result:

MYPREPENDSTRING\my.username

Second goal: After that I would need another REGEX that can extract the ip address in this line that starts with IP- (IP-192.168.250.100). Final result:

Wanted result:

192.168.250.100

These two goals have to be done only with regex... don't know if it's possible.

Much appreciated!!

CodePudding user response:

username-(?<username>[a-zA-Z0-9\.-_]*),.*IP-(?<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}),

Test

Assuming that username can be alphanumeric and contain dots, dashes and underscores.

Also assuming that the ip is always after the username in the log lines.

  • IP-(?<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}), will match the IPv4 address in a group named ip (note that this will accept 999.999.999.999 as a valid IP4v address)
  • username-(?<username>[a-zA-Z0-9\.-_]*), will match the username in a group named username.

CodePudding user response:

That should do the trick:

(?<=username-)(\w \.\w ).*?IP-((\d{1,3}\.){3}(\d{1,3}))

The username is in your first capturing group and the IP in the second. Note that this will only work with IPv4 addresses.

Example

Explanation:

(?<=username-)(\w \.\w ).*?IP-((\d{1,3}\.){3}(\d{1,3}))
(?<=         )                                          #positive lookbehind
    username-                                           #matches text "username-"
              (        )                                #capturing group 1
               \w \.\w                                  #matches any word character between 1 and infinity, followed by a dot "." followed by any word character
                        .*?                             #matches any character between 0 and infinity, non greedy
                           IP-                          #matches the string "IP-"
                              (                       ) #second canturing group
                               (\d{1,3}\.)              # matches any digit between 1 to 3 times, followed by a dot "."
                                          {3}           #quantifies previous match 3 times
                                             (\d{1,3})  #matches any digit between 1 to 3 times
  • Related