[英].net Regex Search and string.replace
我的xml文件大約7mb。 我必須從某些節點中刪除一些無效字符。 有很多節點,例如“ title”,“ country”等等。
我的“ title”節點有31000個匹配項,並且花費了超過35分鍾的時間。 我的項目要求不可接受,我該如何優化
方法調用
fileText = RemoveInvalidCharacters(fileText, "title", @"(&#[xX]?[A-Fa-f\d]+;)|[^\w\s\/\;\&\.@-]", "$1");
方法定義
private static string RemoveInvalidCharacters(string fileText, string nodeName, string regexPattern, string regexReplacement)
{
foreach (Match match in Regex.Matches(fileText, @"<" + nodeName + ">(.*)</" + nodeName + ">"))
{
var oldValue = match.Groups[0].Value;
var newValue = "<" + nodeName + ">" + Regex.Replace(match.Groups[1].Value, regexPattern, regexReplacement) +
"</" + nodeName + ">";
fileText = fileText.Replace(oldValue, newValue);
}
return fileText;
}
您可以使用System.Xml.Linq
命名空間中的工具來代替您使用Regex
來解析Xml文檔,這本質上是更快,更容易使用。
這是一個示例程序,它采用的結構包含35,000個節點。我保留了您的regex字符串以檢查不良字符,但我將其指定為Compiled
regex字符串,這應該會產生更好的性能,盡管公認的是,當我將兩者進行比較時,數量會大大增加。 更多信息 。
本示例使用Descendants
,它獲取對您在指定元素內的參數中指定的所有元素的引用(在本例中,我們從根元素開始)。 這些結果通過ContainsBadCharacters
方法進行過濾。
為了簡單起見,我沒有將foreach
循環設為DRY,但是這樣做可能是值得的。
在我的計算機上,此過程運行的時間不到一秒鍾,但是時間會根據計算機的性能和不良字符的出現而有所不同。
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
static Regex r = new Regex(@"(&#[xX]?[A-Fa-f\d]+;)|[^\w\s\/\;\&\.@-]", RegexOptions.Compiled);
static void Main(string[] args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
var xmls = new StringBuilder("<Nodes>");
for(int i = 0;i<35000;i++)
{
xmls.Append(@"<Node>
<Title>Lorem~~~~</Title>
<Country>Ipsum!</Country>
</Node>");
}
xmls.Append("</Nodes>");
var doc = XDocument.Parse(xmls.ToString());
sw.Start();
foreach(var element in doc.Descendants("Title").Where(ContainsBadCharacters))
{
element.Value = r.Replace(element.Value, "$1");
}
foreach (var element in doc.Descendants("Country").Where(ContainsBadCharacters))
{
element.Value = r.Replace(element.Value, "$1");
}
sw.Stop();
var saveFile = new FileInfo(Path.Combine(Assembly.GetExecutingAssembly().Location.Substring(0,
Assembly.GetExecutingAssembly().Location.LastIndexOf(@"\")), "test.txt"));
if (!saveFile.Exists) saveFile.Create();
doc.Save(saveFile.FullName);
Console.WriteLine(sw.Elapsed);
Console.Read();
}
static bool ContainsBadCharacters(XElement item)
{
return r.IsMatch(item.Value);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.