2011-08-12 10 views
1

i「は$私はそれは私が望むようなこの正規表現置き換え変数は

<? 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

関連する問題