我做了這樣的事情在幾個月前,並認爲這可能是一起的,你在找什麼...
c:\Perl>perl StackOverflow.pl
SomeValue
AND
-operator1
--operator2
---x
---a
--operator3
---y
---b
-operator4
--t
c:\Perl>
如果是這樣,這裏的代碼(下)行。這有點混亂,但它應該足以讓你開始。
#!c:/perl/bin/perl.exe
my $SourceString="SomeValue AND (operator1(operator2(x,a),operator3(y,b)),operator4(t))";
my $NodeIndex=0;
my $IndexString="-";
print ProcessString($SourceString, $NodeIndex);
exit;
#----- subs go here -----
sub ProcessString {
my $TargetString=shift||return undef;
my $NodeIndex=shift;
my $ReturnString="";
#are we starting with a paren or comma?
if($TargetString=~m/^([\(\)\, ])/) {
#yep, delete the char and pass it through again for further processing
if($1 eq " ") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
elsif($1 eq ",") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
elsif($1 eq "(") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), ++$NodeIndex);}
elsif($1 eq ")") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), --$NodeIndex);}
} else {
#nope, must be a keyword or the end
if($TargetString=~m/([\(\)\, ])/) {
my $KeywordString=substr($TargetString, 0, index($TargetString, $1));
$ReturnString.=$IndexString x $NodeIndex;
$ReturnString.=$KeywordString."\n";
$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)), $NodeIndex);
} else {
#we should never be here
} #end keyword check if
} #end if
#send the string back
return $ReturnString;
} #end sub
__END__
定義「可視化」。你想打印出一個操作符和操作數的樹嗎?或者是其他東西? – ThisSuitIsBlackNot
請編輯問題以提高問題的可讀性o/p – Gaurav
問題不清楚,但很可能需要創建語法分析器。你可以使用遞歸正則表達式匹配。還請看看[Regexp :: Grammars](http://search.cpan.org/~dconway/Regexp-Grammars-1.033/lib/Regexp/Grammars.pm) – alex