C尖锐的替换功能 [英] C sharp Replace Function
问题描述
大家好,
我有一种情况需要将
Hi All,
I have a scenario where i need to replace
标签
初始代码
tag
Initial Code
<div> some text </div>
<div style="any style"> more text</div>
-----------------实施代码--------------------------------- --------------------
-----------------Code implemented---------------------------------------------------
<div> replaced with <br>
</div> replaced with String.Empty
<div style="any style"> not getting replaced :(
-------------------------------------------------- ----------------------------------
- - - - - - - - - - - - 代码 - - - - - - - - - - - - - -------------------------------
------------------------------------------------------------------------------------
------------------------Code--------------------------------------------------------
public string ReplaceDivTagToBrakeTag(string data)
{
return data.Replace("<div>","<br>").Replace("</div>", String.Empty)).ToString();
}
-------------------------------------------------- ----------------------------------
最终输出
------------------------------------------------------------------------------------
Final Output
<br> some text
<br> more text
问题:
替换简单的
The problem:
It''s easy to replace the simple
请提供解决方案:)
Please provide a solution :)
推荐答案
using System.Text.RegularExpressions;
[...]
[...]
private string ReplaceDivTagToBrakeTag(string data)
{
Regex regEx = new Regex(@"<div.*>(.*)</div>");
Match m = regEx.Match(data);
return "<br>" + m.Groups[1].Value.Trim();
}
您需要单独处理(带有div的样式)........
You need to handle it (style with div) separately........
data.Replace("<div>", "<br>").Replace("</div>", String.Empty).Replace("<div style=any style>", "<br>").ToString();
所以也许您会将这些数据解析为XML.
http://msdn.microsoft.com/zh-cn/library/cc189056%28v=vs.95%29.aspx
这样,您就不必在每次数据更改时都进行更改.
我不确定xml解析器是否足以满足此要求.如果您的数据足够简单并且格式正确,我应该这样做.对于更复杂的情况,请使用非标准HTML解析器库之一( http://htmlagilitypack.codeplex.com/ [
So maybe you will parse this data as XML.
http://msdn.microsoft.com/en-us/library/cc189056%28v=vs.95%29.aspx
This way you will not have to change it everytime data will change.
I am not sure if xml parser will be sufficient for this. I should if your data will be simple enough and formatted correctly. For more complicated cases use one of non standard HTML parser libraries (http://htmlagilitypack.codeplex.com/[^] this looks promising).
As for parsing it with regex read:
http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
I know that RegExp is simple, but you have problems already with this, and with RegExp and Html are always problems (been there, done that and it will not happen again).
这篇关于C尖锐的替换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!