2011-08-12 26 views
1

我有一個像正則表達式替換變量指針代替

<? if $items.var1.var2 == $items2.var1.var2 ?> 

我想替換的字符串,它看起來像這樣

<? if $items->{var1}->{var2} == $items2->{var1}->{var2} ?> 

所以串呀,我想替換字符串中沒有報價「$ items2.var1.var2' 串像這樣

<? if $items.var1.var2 == '$items2.var1.var2' ?> 

誰能幫助我?

回答

0

因此,只有在後面跟着偶數個引號時,您才需要替換點/變量。在Python,例如:

>>> re.sub(r"\.(\w+)(?=(?:[^']*'[^']*')*[^']*$)", r"->{\1}", 
...   "<? if $items.var1.var2 == '$items2.var1.var2' ?>") 
"<? if $items->{var1}->{var2} == '$items2.var1.var2' ?>" 

說明:

\.  # Match . 
(\w+) # Match an alnum word and capture it 
(?=  # Assert that it's possible to match: 
(?:  # Match this (don't capture): 
    [^']*' # Any number of non-quotes, followed by a ' 
    [^']*' # The same again 
)*  # any number of times, including 0 
[^']* # Match any number of non-quotes 
$  # until the end of the string. 
)  # End of lookahead assertion. 
+0

謝謝!我該如何替換這隻在標籤之間? – Timay

+0

這就是正則表達式開始不成爲選擇工具的地方,以及需要解析器的地方。或者,首先匹配'<\?.*?\?>',然後將第一個正則表達式應用於這些匹配。 –

0

這個工作在Perl:

$str =~ s/\.(?=(\w|\.)+(?!'|"|\.)\W)/->/g; 
#explained: 
$str =~ s/ 
     \.    #A literal . 
     (?=   #Followed by 
      (\w|\.)+  #More than one word char or literal . 
      (?!'|"|\.) #Terminated by a \W (non-word char) that's not ',", or . 
      \W 
     ) 
     /->/gx; 

至少在你的例子。 http://codepad.org/a4L43hDr