Home > Back-end >  Need help in creating regex, not able to get second group of match pattern
Need help in creating regex, not able to get second group of match pattern

Time:02-04

I'm trying to create regex for below data to parse, but not able to get second matched pattern 2.2.2.2 testIp2. As don't have much exposure on regex, struggling since almost 12 hours.

Data to be parsed:

show names
names 1.1.1.1 testIp1 2.2.2.2 testIp2
name 192.168.1.1 testIp3
umesh 192.168.1.2 testIp4

The regex I could create:

^(?:name|names)(?:\s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s (\S ))

Here is my perl code snippet:

while( $data =~ /^(?:name|names)(?:\s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s (\S ))/mg) {
    $LOGGER->debug("IPs : $1 : $2");
}

enter image description here

In the screenshot below, please check ip 2.2.2.2 testIP2 not being matched in regex101 tool:

CodePudding user response:

If there can be an arbitrary number of repetitions, it's probably better to extract the tokens and then loop over them using a very simple regex.

if($data =~ /^names?(?:\s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s (\S ))/) {
    my $match = $1;
    while (s/$match/^(\d{1,3}(\.\d{1,3}){3})\s /) {
      $LOGGER->debug("IPs : $1 : $2");
    }
}

CodePudding user response:

Try following regex:

^(?:name|names)(?:\s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s (\S ))(?:\s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s (\S ))*

Here is the demo on regex101: enter image description here

  • Related