[英]Process part of the regex match before replacing it
我正在編寫一個函數,該函數將從舊系統中解析類似於XML文件的文件。
....
<prod pid="5" cat='gov'>bla bla</prod>
.....
<prod cat='chi'>etc etc</prod>
....
.....
我目前有以下代碼:
buf = Regex.Replace(entry, "<prod(?:.*?)>(.*?)</prod>", "<span class='prod'>$1</span>");
在確定我們也要顯示類別之前,一切工作正常。
問題是類別是可選的,我需要通過SQL查詢運行類別縮寫以檢索類別的全名。
例如:
SELECT * FROM cats WHERE abbr='gov'
最終輸出應為:
<span class='prod'>bla bla</span><span class='cat'>Government</span>
關於如何執行此操作的任何想法?
注意1:該功能已經完成(本部分除外)並且工作正常。 注意2:不能使用XML庫,必須使用正則表達式
Regex.Replace
具有一個重載,該重載帶有MatchEvaluator
,它基本上是Func<Match, string>
。 因此,您可以動態生成替換字符串。
buf = Regex.Replace(entry, @"<prod(?<attr>.*?)>(?<text>.*?)</prod>", match => {
var attrText = match.Groups["attr"].Value;
var text = match.Groups["text"].Value;
// Now, parse your attributes
var attributes = Regex.Matches(@"(?<name>\w+)\s*=\s*(['""])(?<value>.*?)\1")
.Cast<Match>()
.ToDictionary(
m => m.Groups["name"].Value,
m => m.Groups["value"].Value);
string category;
if (attributes.TryGetValue("cat", out category))
{
// Your SQL here etc...
var label = GetLabelForCategory(category)
return String.Format("<span class='prod'>{0}</span><span class='cat'>{1}</span>", WebUtility.HtmlEncode(text), WebUtility.HtmlEncode(label));
}
// Generate the result string
return String.Format("<span class='prod'>{0}</span>", WebUtility.HtmlEncode(text));
});
這應該可以幫助您入門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.