我正在使用正则表达式来检测帖子中的论坛标签,例如“[quote]text[/quote]”,然后将它们替换为 HTML 格式。我发布了一个问题 Forum tags. What is the best way to implement them?关于嵌套标签的问题。
我有一个想法,但我需要有人帮助我扩展它(因为我不擅长正则表达式)。
我需要修改这个正则表达式
string regex = @"\[([^=]+)[=\x22']*(\S*?)['\x22]*\](.+?)\[/(\1)\]";
现在,它匹配一个开始和结束标签,标签名称匹配组,标签内容,以及一个可选值,比如这个论坛标签中等号后面的值 [url=www.google.com ]点击我[/url]
。
我需要的是表达式匹配开始标签或结束标签,并有一个包含标签名称的匹配组(包括结束标签的“/”)。然后我想像这样遍历它们:
Dictionary<string, int> tagCollection = new Dictionary<string, int>();
inputString = Regex.Replace(inputString, @"expression I'm asking for here",
match =>
{
string tag = match.Groups[0].Value;
bool isOpeningTag = tag.StartsWith("/");
tag = isOpeningTag ? tag : tag.Replace("/","");
int tagCount = 0;
if (tagCollection.ContainsKey(tag) && isOpeningTag)
{
tagCount = tagCollection[tag];
tagCollection[tag] = tagCount + 1;
}
else if (tagCollection.ContainsKey(tag) && !isOpeningTag)
{
tagCount = tagCollection[tag];
tagCollection[tag] = tagCount - 1;
}
else if (!tagCollection.ContainsKey(tag) && isOpeningTag)
tagCollection.Add(tag, tagCount);
string newTag = match.Value.Replace(tag, tag + tagCount.ToString());
return newTag;
});
现在,每个标签都附加了一个数字,我可以使用原始正则表达式来执行标签功能,并将嵌套标签正确地处理为单独的标签。所以说真的,我只需要你们提供我列出的正则表达式,按照我指定的方式进行修改。
也可以随意提供其他建议,但我会要求实际答案集中在正则表达式修改上,而不是这是否是解决问题的最佳方法。
谢谢!
最佳答案
这可能对您有所帮助,这是我前一段时间编写的 bbcode 解析器,基本上可以完全按照您的要求进行操作。
https://github.com/Mike343/Netcoders/tree/master/Coders.Services/Formatters
https://github.com/Mike343/Netcoders/blob/master/Coders.Services/Formatters/BBCodeFormatter.cs
关于c# - 我需要帮助修改 C# 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111461/