简体   繁体   English

正则表达式将url转换为超链接

[英]Regular expression convert url to hyperlink

I've googled some code that converts an url into a hyperlink using bbcode The code is : 我已经搜索了一些使用bbcode将URL转换为超链接的代码,代码是:

// format the url tags: [url=www.website.com]my site[/url]
// becomes: <a href="www.website.com">my site</a>
exp = new Regex(@"\[url\=([^\]]+)\]([^\]]+)\[/url\]");
str = exp.Replace(str, "<a href=\"$1\">$2</a>");

// format the img tags: [img]www.website.com/img/image.jpeg[/img]
// becomes: <img src="www.website.com/img/image.jpeg" />
exp = new Regex(@"\[img\]([^\]]+)\[/img\]");
str = exp.Replace(str, "$1\" />");

I also want to convert ordinary links hyperlinks.I've googled some more and got this: 我也想转换普通链接的超链接。我在Google上搜索了更多内容:

exp = new Regex("(http://[^ ]+)");
str = exp.Replace(str, "<a href=\"$1\">$1</a>");

The problem is, when i mix them and third regular expression is executed, the first two will be messed up. 问题是,当我混合它们并执行第三个正则表达式时,前两个将被弄乱。 as it could result in : 因为它可能导致:

<img src="<a href='www.website.com/img/image.jpeg>www.website.com/img/image.jpeg</a>" />

how can i specify in my third regular expression that he cannot convert strings that begin with 'href="' or 'src="' ? 如何在我的第三个正则表达式中指定他不能转换以'href =“'或'src =”'开头的字符串?

Given the interesting combinations of tags users could throw at you, regular expressions quickly become cumbersome and difficult to use for parsing tags. 鉴于用户可能会向您扔掉有趣的标签组合,因此正则表达式很快变得笨拙且难以解析标签。

BBCode is essentially a grammar unto itself, and the best way to interpret a grammar programmatically is with an actual parser. BBCode本质上是一种语法,以编程方式解释语法的最佳方法是使用实​​际的解析器。

Have a look at http://bbcode.codeplex.com/ . 看看http://bbcode.codeplex.com/ I can't vouch for its effectiveness, but they've implemented a parser for BBCode in C# that might do what you're looking for. 我不能保证它的有效性,但是他们已经在C#中为BBCode实现了一个解析器,该解析器可能会满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM