多行字符串替换为漂亮的缩进 [英] Multiline string replace with pretty indentation

查看:141
本文介绍了多行字符串替换为漂亮的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在某些模板文件中进行多行字符串替换,但要保留漂亮的缩进.

I want to do multi-line string replacements in some template files, but retain a pretty indentation.

这是模板的示例:

<TAG1>
    <TAG2>
        %REPLACETHIS%
    </TAG2>
</TAG1>

现在,当我简单地将字符串%REPLACETHIS%替换为类似的字符串

Now, when I simply replace the string %REPLACETHIS% with a string like

<REPLACEDSTRINGTAG1>
    replacedstringtext
</REPLACEDSTRINGTAG1>

它看起来像:

    <TAG1>
        <TAG2>
            <REPLACEDSTRINGTAG1>
    replacedstringtext
</REPLACEDSTRINGTAG1>
        </TAG2>
    </TAG1>

看起来应该是这样的:

    <TAG1>
        <TAG2>
            <REPLACEDSTRINGTAG1>
                replacedstringtext
            </REPLACEDSTRINGTAG1>
        </TAG2>
    </TAG1>

它变得更加复杂,因为模板将成为更大模板的一部分,在模板中也应正确缩进.

It gets even more complicated because the template will be part of a bigger template where it should be indented correctly as well.

我正在尝试在Perl中实现这一目标,但是基本上,我所知道的所有语言中的问题都是相同的.

I'm trying to achieve this in Perl, but basically the problem is the same in all the languages I know.

还有什么比用跟踪当前缩进深度的变量逐行替换更好的主意吗?由于具有多级模板结构,因此非常麻烦.

Has anyone a better idea than to just replace line-by-line with variables that keep track of the current indent depth? Which is very cumbersome due to the multi-level-template structure.

基本上,我需要的是替代一个简单的正则表达式,该表达式不仅会将替换字符串的第一行放在右列,而且还将每一行都放在该列上.因此,如果%REPLACETHIS%位于第10列,则替换字符串中的所有行都应放在第10行...也许Perl中有一些带有正则表达式的内置魔术?

Basically, what I need is a substitute for a simple regex that will not only put the first line of the substitution string at the right column, but puts every line on that column. So if %REPLACETHIS% is at column 10, all the lines in the replacement string should be put at col 10... maybe there is some tricky built-in magic with regexes in Perl?

推荐答案

现在,您的模板文件为XML格式,您可以使用一些XML处理模块来处理它.更灵活,更可靠.

Now that your template files are in XML format, you could use some XML processing modules to handle it. It's more flexible and reliable.

对于您的情况, XML :: LibXML 可以完美处理:

For your case, XML::LibXML could handle perfectly:

use XML::LibXML;
use XML::LibXML::PrettyPrint;

my $xml = "template.xml";
my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($xml);
my $root = $tree->getDocumentElement;

my ($replace_node) = $root->findnodes('/TAG1/TAG2');
$replace_node->removeChildNodes();
my $new_node = $tree->createElement('REPLACEDSTRINGTAG1');
$new_node->appendText('replacedstringtext');
$replace_node->addChild($new_node);

my $pp = XML::LibXML::PrettyPrint->new(indent_string => "\t");
$pp->pretty_print($tree);
print $tree->toString;

这篇关于多行字符串替换为漂亮的缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆