我已经到处寻找一个可以在C#中使用的正则表达式,但却无法获得任何结果。我发现了很多PHP但不确定如何将它转换为C#。所以我想要做的只是创建一个正则表达式,递归匹配引号的bbcode,然后将其更改为HTML。这是一个例子:
[quote="bob"]I can't believe that you said this: [quote="joe"]I love lamp.
[/quote] That's hilarious![/quote]
那应该变成:
<fieldset class="bbquote"><legend>bob</legend>I can't believe that you said
this: <fieldset class="bbquote"><legend>joe</legend>I love lamp.</fieldset>
That's hilarious!</fieldset>
我尝试过的所有正则表达式都失败了。
答案 0 :(得分:0)
你可以试试这个:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String sample = "[quote=\"bob\"]I can't believe that you said this: [quote=\"joe\"]I love lamp.[/quote] That's hilarious![/quote]";
Regex regex = new Regex(@"(?:(?:\[quote="")(\w+)(?:""\])?([^\[]+))(?:(?:\[quote="")(\w+)(?:""\])?([^\[]+))(?:[^\]]+\]\s)([^\[]+)(?:\[\/quote\])");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(regex.Replace(sample,"<fieldset class=\"bbquote\"><legend>$1</legend>$2<fieldset class=\"bbquote\"><legend>$3</legend>$4</fieldset>$5</fieldset>"));
}
}
}
它捕获了5组:
你可以替换为:
<fieldset class="bbquote"><legend>bob</legend>I can't believe that you said this: <fieldset class="bbquote"><legend>joe</legend>I love lamp.</fieldset>That's hilarious!</fieldset>
答案 1 :(得分:0)
没有必要以递归方式执行此操作或匹配引用的相应开头和结尾 - 最后,必须替换相同数量的开始和结束。这可以通过e进行任何嵌套来实现。 g。:
void Main()
{
String s = "[quote=\"bob\"]I can't believe that you said this: [quote=\"joe\"]I love lamp.[/quote] That's hilarious![/quote]";
Regex r = new Regex(@"\[quote=""(\w+)""\](.*?)\[/quote]");
while (r.Match(s).Success)
s = r.Replace(s, "<fieldset class=\"bbquote\"><legend>$1</legend>$2</fieldset>");
Console.WriteLine(s);
}