Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse nslookup result by regex

Tags:

regex

php

I have 2 different nslookup results:

Server:  PROXY.LOCAL
Address:  192.168.1.1

Name:    google.com
Addresses:  2a02:598:2::1168
     77.75.77.168

and

Server:  router.local
Address:  192.168.1.1

DNS request timed out.
    timeout was 3 seconds.
Name:    google.com
Address:  216.58.207.46

My regex code looks like this:

$re = '~(?:Name:\s*\S+\s*)\K(?:\G(?!\A)|^Addresses:|^Address:)\s*\K\S\S\S+~m';

Problem is that when Addresses: exists it will return only first IP, not second one on new line.

like image 501
step Avatar asked Jan 22 '26 02:01

step


1 Answers

The main issue with your approach is that you "anchored" the match at the (?:Name:\s*\S+\s*)\K pattern. The \K operator does not make the preceding pattern non-consuming, and that text must appear for a match to occur.

You should make sure the pattern adheres to a scheme like:

(?:\G(?!\A)|<START_PATTERN>)<PATTERN_TO_CONSUME_AND_OMIT>\K<PATTERN_TO_EXTRACT>

That is, your current pattern follows the abc\s+(?:\G(?!\A)|d)\s*\K\S+ scheme, and it should be (?:\G(?!\A)|abc\s+d)\s*\K\S+.

You may fix it using

'~(?:\G(?!\A)\R\h+|^Name:\s*\S+\s*Address(?:es)?:)\s*\K\S+~m'

See the regex demo.

It matches

  • (?:\G(?!\A)\R\h+|^Name:\s*\S+\s*Address(?:es)?:) - either the end of the previous match (\G(?!\A)) + a line break and 1+ horizontal whitespace chars (\h+) or (|) a sequence of the following patterns:
    • ^ - start of a line
    • Name: - a literal substring
    • \s* - 0+ whitespaces
    • \S+ - 1+ non-whitespace chars
    • \s* - 0+ whitespaces
    • Address - a literal substring
    • (?:es)? - an optional non-capturing group matching es substring 1 or 0 times
    • : - a colon
  • \s* - 0+ whitespaces
  • \K - match reset operator (discarding all the text matched so far)
  • \S+ - 1+ non-whitespace chars.

Note I added \h+ after \G(?!\A) to make sure the next line starts with 1+ horizontal whitespaces, in order to stop matching if the next line starts with a non-whitespace char.

like image 194
Wiktor Stribiżew Avatar answered Jan 23 '26 21:01

Wiktor Stribiżew