[英]Regex pattern BBCode to Wiki Notation, C#
我的任務是將BB代碼轉換為WIKI表示法,並將thanx轉換為許多示例,因此我已經破解了大多數較難的內容。 這是我對Regex的首次嘗試,我正在嘗試學習它( 我更喜歡stringbuilder,但它似乎不適用於BB代碼 )。 我有4個需要替換的項目,我似乎無法創建合適的模式來識別:( 原始字符串在左側,雙破折號之后我需要在右側 )
第一項是問題子級,因為Wiki引擎在空格所在的位置添加了新行。 它不是一個單獨的字段,而是較大字符串的一部分,因此我無法對其進行TRIM()。 我目前正在使用
result = result.Replace("[b]", "*").Replace("[/b]", "*");
img問題是需要以某種方式包括給定格式的屬性。
對於最后的2我感到難過。 我用過
Regex r = new Regex(@"<a .*?href=['""](.+?)['""].*?>(.+?)</a>");
foreach (var match in r.Matches(multistring).Cast<Match>().OrderByDescending(m => m.Index))
{
string href = match.Groups[1].Value;
string txt = match.Groups[2].Value;
string wikilink = "[" + txt + "|" + href + "]";
sb.Remove(match.Groups[2].Index, match.Groups[2].Length);
sb.Insert(match.Groups[2].Index, wikilink);
}
在過去的HTML中,但似乎無法根據我的當前需求對其進行重構。 建議,資源鏈接,將不勝感激。
EDIT解決了img問題,盡管它不是很漂亮,但我仍然冒着刪除一個可能不及早捕獲的結束[/ img]標記的風險。 [img]代碼相當一致,所以我使用了:
Regex imgparser = new Regex(@"\[img[^\]]*\]([^\[]*)");
foreach (var itag in imgparser.Matches(multistring).Cast<Match>().OrderByDescending(m => m.Index))
{
string isrc = itag.Groups[1].Value;
string wikipic = itag.ToString().Replace("[img ", "!" + isrc).Replace("width=", "!width=").Replace("height=", ",height=").Replace("]" + isrc, string.Empty);
result = result.Replace(itag.ToString(), wikipic);
}
result = result.Replace("[/img]", "!");
我可以舉一個最后的例子:
string str1 = "[url=http://aadqsdqsd]link[/url]";
var pattern = @"^\[url=(.*)\](.*)\[\/url\]$";
var match = Regex.Match(str1, pattern);
var result = string.Format("[{0}| {1}]", match.Groups[2].Value, match.Groups[1].Value);
//[link| http://aadqsdqsd]
是你想要的嗎?
編輯
如果要匹配更大的字符串,可以執行以下操作:
var strTomatch = "[url=http://1]link1[/url][url=http://2]link2[/url]" + Environment.NewLine +
"[url = http://3]link3[/url]" + Environment.NewLine +
"[url=http://4]link4[/url]";
var match = Regex.Match(strTomatch, @"\[url\s*=\s*(.*?)\](.*?)\[\/url\]", RegexOptions.Multiline);
while (match.Success)
{
var result = string.Format("[{0}| {1}]", match.Groups[2].Value, match.Groups[1].Value);
Debug.WriteLine(result);
match = match.NextMatch();
}
輸出量
[link1| http://1]
[link2| http://2]
[link3| http://3]
[link4| http://4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.