开发者

Regex replace variables pointer replace

i have a string like

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

i want to replace the string that it looks like this

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

So strings like that i want to replace not quoted '$items2.var1.var2' strings like this

 <? if $items.var1.var2 == '$items2.var1.var2' ?>
开发者_开发问答

Can anyone help me?


So you need to replace dots/variables only if they are followed by an even number of quotes. In Python, for example:

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

Explanation:

\.       # 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.


This works in 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;

At least for your examples. http://codepad.org/a4L43hDr

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜