Deano Deano - 7 months ago 13
Perl Question

How to extract unix path in perl

Input

[security] [client 198.66.91.7] [domain testphp.example.com] [200] [/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD] (null)


Desired output

/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD


here is what I have so far

'.*?\[.*?\].*?\[.*?\].*?\[.*?\].*?\[.*?\].*?\[(.*?)\]'


My Perl code.

#!/usr/bin/perl
use feature 'say';

$txt='[modsecurity] [client 199.66.91.7] [domain testphp.vulnweb.com] [200] [/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD] (null)';


$re=''.*?\[.*?\].*?\[.*?\].*?\[.*?\].*?\[.*?\].*?\[(.*?)\]'';

if ($txt =~ m/$re/is)
{
$sbraces1=$1;
say $1;
}


output

/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD


I think my regex is messy? maybe another way?

Thanks

Answer

I would use a split too... or a more general regex than the one you are using:

#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my $data = '[security] [client 198.66.91.7] [domain testphp.example.com] [200] [/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD] (null)';

my @fields = $data =~ /(?:\[(.*?)\])+/g;

print Dumper(\@fields);

The output you get is:

$VAR1 = [
          'security',
          'client 198.66.91.7',
          'domain testphp.example.com',
          '200',                                                                                                                               
          '/apache/20160503/20160503-0636/20160503-063628-Vyh-LH8AAAEAAE6zC@AAAAAD'                                                            
        ];         

So the fifth element of the returned array is what you want.