我怎样才能替换 <和 >在 xml 文件的内容中使用正则表达式? [英] How can I replace < and > in the content of xml file using regex?

查看:36
本文介绍了我怎样才能替换 <和 >在 xml 文件的内容中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何替换<"和一个 ">"(在 xml 文件的内容中)具有匹配的 "&lt;""&gt;"(带有一组预先知道的标签)使用正则表达式?

How can i replace a "<" and a ">" (in the content of xml file) with a matching "&lt;" and "&gt;" (with a pre known set of tags) using a regex?

示例:<abc>fd<jkh</abc><def>e>e</def> 应该得到:<abc>fd&lt;jkh</abc><def>e&lt;e</def>

它必须用正则表达式完成!(没有 xml 加载等等...)

it must be done with a regex! (no xml load and such...)

推荐答案

我认为的模式

<([^>]*<)

将匹配在 > 之前遇到另一个 <<(因此不是标签的一部分)

will match a < that encounters another < before > (therefore not part of a tag)

...和模式

(>[^<]*)>

将匹配另一个 >>

var first = Regex.Replace(@"<abc>fd<jkh</abc><def>e>e</def>",@"<([^>]*?<)",@"&lt;$1");
var final = Regex.Replace(first,@"(>[^<]*?)>",@"$1&gt;");

这确实有效,但您必须多次跳过它.我确定有更纯粹的方法,但这确实有效.

This does work, but you have to pass over it multiple times. I'm sure there's a purer method, but this does work.

class Program
{
    static void Main(string[] args)
    {
        var next = @"<abc>dffs<<df</abc>";
        string current;
        do
        {
            current = next;
            next = Regex.Replace(current, @"<([^>]*?<)", @"&lt;$1");
            next = Regex.Replace(next, @"(>[^<]*?)>", @"$1&gt;");
        } while(next != current);
        Console.WriteLine(current);
        Console.ReadKey();
    }
}

这篇关于我怎样才能替换 &lt;和 &gt;在 xml 文件的内容中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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