我有一个像
这样的字符串<? 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 :(得分: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.
答案 1 :(得分: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