coloneltsanders coloneltsanders - 2 months ago 14
Perl Question

Parsing text file with Perl

I am trying to parse a file like the one below in perl. I want what's to the left of the : to be the name of the variable and what's to the right of the : as the string/integer assigned to the variable. I would like to print out the results where it will have the variable on the left and the string/int on the right.

Thanks!

"StopSequence" : "1",
"StopType" : 1,
"StopScheduledDatePart" : "2016-09-08",
"StopScheduledStartTimePart" : "22:00:00",
"StopReference" : "1",
"StopContactPhoneNumber" : null,
"StopContactFaxNumber" : null,
"StreetAddress1" : "915 TITAN DRIVE",
"City" : "SOMEWHERE",
"State" : "USA",
"PostalCode" : "46002",
}, {
"StopSequence" : "2",
"StopType" : 3,
"StopScheduledDatePart" : "2016-09-12",
"StopScheduledStartTimePart" : "08:00:00",
"StopSequence" : "1",
"StopType" : 1,
"StopScheduledDatePart" : "2016-09-08",
"StopScheduledStartTimePart" : "22:00:00",

Answer
use strict;

use warnings;

open ( my $fh, "<", "c:\\users\\username\\desktop\\data.txt");

while( my $line = <$fh>){
    if ( $line =~ /\"(.*)\"\s+:\s+\"(.*)\"/){
        if ((defined $1) and (defined $2)){
            print "\nLeft value:$1\nRight value: $2\n";
        }
    }
}

The values captured in $1 and $2 are the left and the right value.
.* is a greedy match, but because it's used in a group delimited by " it won't match all your string, just the needed one.

For your information: SO is not a place for "I want this and i expect you guys to solve it for me". This is basic regex and by doing some google research you could have easily solve it. I would also recomend to try your regexes here before and after you tryed something come with questions.