This regular expresion is not good !!!
---------------------
if ($line=/(.*)=(.*)(#+.*)/){
my ($val,$key,$comment)=($1,$2,$3);
print "Match line : key($key)=val($val) c($comment) \n";

}
---------------------
Example os inputs and the wanted output :
a=b #c => key(a)=val(b) c(#c)
a=b => key(a)=val(b) c()
a="b#" => key(a)=val("b#") c()
a="b#"#ff => key(a)=val("b#") c(#ff)
a="b"#"#ff => key(a)=val("b") c(#"#ff)

Some one can help?

Recommended Answers

All 3 Replies

I'm not sure if your goal is to write a single regex to do this for you...but I wasn't able to get anything to work...here is what i came up with for you...

foreach my $row (@rows){
    if ($row =~ /^.+?=".+?"/){
        $row =~ /^(.+?)=(".+?")\s*((#.*)?)/;
        print "key($1)=val($2) c($3)\n";
    }
    else {
        $row =~ /^(.+?)=(.+?)\s*((#.*)?)/;
        print "key($1)=val($2) c($3)\n";
    }
}

...so its checking to see if your value is in quotes...if so it uses one regex, otherwise it uses the other. That was the easiest way I found of doing it....i wasn't able to get a single regex to do that...I'm sure it is possible..but you'll probably need to look into using lookaround assertions for that.

print "$1, $2, $3", $/ if ($line =~ /(\w+)=(\".+?\"|\'.+?\'|.+)\s*(#.*|)/); katharnakh.

katharnakh - you were close, except it doesn't work for shaybery's first test case....this does however

print "key($1)=val($2) c($3)", $/ if ($line =~ /(\w+)=(\".+?\"|\'.+?\'|.+?)\s*(#.*|)/);

that last ? was missing....which caused $2 to be "b #c" instead of just b...the last .+ needs to be more greedy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.