使用2個正則表達式。第一個匹配一般形式,第二個處理內部管道。
對於XML編碼,我在System.Security中使用了一個不起眼的小方法:SecurityElement.Escape Method。我在下面的代碼中完全限定了它的重點。另一種選擇是使用HttpUtility.HtmlEncode method,但可能涉及對System.Web的引用,具體取決於您使用的位置。
string[] inputs = { @"[% 'test' <mtd:ddl id=""asdf"" runat=""server""/> & <%= Integer.MaxValue %> %]",
@"[% 'test' <mtd:ddl id=""asdf"" runat=""server""/> & <%=Integer.MaxValue %> %]",
@"[% 'test' <mtd:ddl id=""asdf"" runat=""server""/> & <%# Integer.MaxValue%> %]",
@"[% 'test' <mtd:ddl id=""asdf"" runat=""server""/> & <%#Integer.MaxValue%> %]",
};
string pattern = @"(?<open>\[%)(?<content>.*?)(?<close>%])";
string expressionPattern = @"(?<content>.*?)(?<tag><%(?:[=#]))\s*(?<expression>.*?)\s*%>";
foreach (string input in inputs)
{
string result = Regex.Replace(input, pattern, m =>
m.Groups["open"].Value +
Regex.Replace(m.Groups["content"].Value, expressionPattern,
expressionMatch =>
System.Security.SecurityElement.Escape(expressionMatch.Groups["content"].Value) +
expressionMatch.Groups["tag"].Value + " " +
expressionMatch.Groups["expression"].Value +
" %>"
) +
m.Groups["close"].Value
);
Console.WriteLine("Before: {0}", input);
Console.WriteLine("After: {0}", result);
}
結果:
Before: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%= Integer.MaxValue %> %]
After: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%= Integer.MaxValue %> %]
Before: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%=Integer.MaxValue %> %]
After: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%= Integer.MaxValue %> %]
Before: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%# Integer.MaxValue%> %]
After: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%# Integer.MaxValue %> %]
Before: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%#Integer.MaxValue%> %]
After: [% 'test' <mtd:ddl id="asdf" runat="server"/> & <%# Integer.MaxValue %> %]
編輯:,如果你不小心保存開/最終結果關閉[%%]然後將模式更改爲:
string pattern = @"\[%(?<content>.*?)%]";
然後務必刪除對m.Groups["open"].Value
和0的引用。
您所描述的邏輯是由性格比正則表達式解析字符串的性格變得更多的任務。 – Cascabel 2009-09-01 16:05:21
同意Jefromi。這是一些代碼工作(可能利用一或兩個正則表達式) – 2009-09-01 16:10:24