我建立一个论坛,我希望能够用简单的方括号标记,以允许用户设置文本格式。我通过解析字符串,寻找标记当前实现这一点。这是非常繁琐的,特别是当我遇到这样的[URL = HTTP://www.something.com]标记某些文本[/ URL]。不必解析属性和价值,并确保它具有正确的开始和结束标记是一种痛苦,似乎傻了。我知道正EX pressions多么强大,但我不擅长他们,他们挫败我没有尽头。
I am building a forum and I want to be able to use simple square bracket tags to allow users to format text. I am currently accomplishing this by parsing the string and looking for the tags. It's very tedious, especially when I run into a tag like this [url=http://www.something.com]Some text[/url]. Having to parse the attribute, and the value, and make sure it has proper opening and closing tags is kind of a pain and seems silly. I know how powerful regular expressions are but I'm not good at them and they frustrate me to no end.
任何你正则表达式大师愿意帮助我吗?我认为,一个例子就是让我开始。就在正则表达式查找标签,如[B]黑体字[/ B]和标签与像我上面列出的将是有益的链接属性之一。在此先感谢!
Any of you regex gurus willing to help me out? I think an example would get me started. Just a regex for finding tags like [b]bolded text[/b] and tags with attributes like the link one I listed above would be helpful. Thanks in advance!
编辑:也很有帮助链接外行的话来说教程正则表达式
Links to laymen's terms tutorials for regex are also helpful.
这应该工作。而= something.com是可选的,可容纳单或双引号,同时也可以确保关闭标签开始标签相匹配。
This should work. The "=something.com" is optional and accommodates single or double quotes and it also makes sure that the closing tag matches the opening tag.
protected void Page_Load(object sender, EventArgs e)
{
string input = @"My link: [url='http://www.something.com'][b]Some text[/b][/url] is awesome. Jazz hands activate!!";
string result = Parse(input);
}
//Result: My link: <a href="http://www.something.com"><b>Some text</b></a> is awesome. Jazz hands activate!!
private static string Parse(string input)
{
string regex = @"\[([^=]+)[=\x22']*(\S*?)['\x22]*\](.+?)\[/(\1)\]";
MatchCollection matches = new Regex(regex).Matches(input);
for (int i = 0; i < matches.Count; i++)
{
var tag = matches[i].Groups[1].Value;
var optionalValue = matches[i].Groups[2].Value;
var content = matches[i].Groups[3].Value;
if (Regex.IsMatch(content, regex))
{
content = Parse(content);
}
content = HandleTags(content, optionalValue, tag);
input = input.Replace(matches[i].Groups[0].Value, content);
}
return input;
}
private static string HandleTags(string content, string optionalValue, string tag)
{
switch (tag.ToLower())
{
case "url":
return string.Format("<a href=\"{0}\">{1}</a>", optionalValue, content);
case "b":
return string.Format("<b>{0}</b>", content);
default:
return string.Empty;
}
}
现在我只是有这个乐趣。我清理了一下,换成了与\ X22所以整个字符串可以很容易地按@Brad佳士得的建议进行转义。另外,如果有这个正则表达式不会打破[或]字符的内容。也它处理递归的标签
Now i'm just having fun with this. I cleaned it up a bit and replaced the " with \x22 so the entire string can easily be escaped per @Brad Christie's suggestion. Also this regex won't break if there are "[" or "]" characters in the content. Also it handles tags recursively