2014-01-14 63 views
0

我試圖想象一個公式,就是這種格式的一個字符串:如何變換一個字符串圓括號父子represantion

AND(operator1(operator2(x,a),operator3(y,b)),operator4(t)) 

有沒有限制多少參數是在運營商。

目前我正試圖在Perl中解決它。我想最簡單的方法是將其轉換爲父子表示,然後它會很容易呈現它在這樣一個可摺疊的方式:

[-]AND(
    [-]operator1(
    [-]operator2(
     x 
     a 
    ) 
    [+]operator3(...) 
) 
    [-]operator4(
    t 
) 
) 

我懷疑我對解決這個第一個,但我在網上找不到任何這樣的例子。謝謝!

+4

定義「可視化」。你想打印出一個操作符和操作數的樹嗎?或者是其他東西? – ThisSuitIsBlackNot

+0

請編輯問題以提高問題的可讀性o/p – Gaurav

+0

問題不清楚,但很可能需要創建語法分析器。你可以使用遞歸正則表達式匹配。還請看看[Regexp :: Grammars](http://search.cpan.org/~dconway/Regexp-Grammars-1.033/lib/Regexp/Grammars.pm) – alex

回答

0

我做了這樣的事情在幾個月前,並認爲這可能是一起的,你在找什麼...

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__ 
相關問題