繁体   English   中英

我需要一个正则表达式将字符串转换为锚标记以用作超链接

[英]I need a regular expression to convert a string into an anchor tag to be used as a hyperlink

嗨,我正在寻找一个会改变这种情况的正则表达式:

[check out this URL!](http://www.reallycoolURL.com)

进入这个:

<a href="http://www.reallycoolURL.com">check out this URL</a>

即用户可以使用我的格式输入URL,我的C#应用​​程序会将其转换为超链接。 我想在C#中使用Regex.Replace函数,任何帮助都将不胜感激!

使用Regex.Replace方法指定替换字符串,以允许您格式化捕获的组。 一个例子是:

string input = "[check out this URL!](http://www.reallycoolURL.com)";
string pattern = @"\[(?<Text>[^]]+)]\((?<Url>[^)]+)\)";
string replacement = @"<a href=""${Url}"">${Text}</a>";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine(result);

请注意,我在模式中使用了命名捕获组,这允许我在替换字符串中将它们称为${Name} 您可以使用此格式轻松构建替换。

模式细分是:

  • \\[(?<Text>[^]]+)] :匹配一个左方括号,并将不是结束方括号的所有内容捕获到指定的捕获组Text中 然后匹配关闭的方括号。 请注意,关闭方括号不需要在字符类组中进行转义。 尽管逃离开口方括号是很重要的。
  • \\((?<Url>[^)]+)\\) :同样的想法,但带括号并捕获到命名的Url组。

命名组有助于清晰,正则表达式可以从他们可以获得的所有清晰度中受益。 为了完整起见,这里使用相同的方法而不使用命名组,在这种情况下,它们被编号:

string input = "[check out this URL!](http://www.reallycoolURL.com)";
string pattern = @"\[([^]]+)]\(([^)]+)\)";
string replacement = @"<a href=""$2"">$1</a>";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine(result);

在这种情况下([^]]+)是第一个组,在替换模式中通过$1引用,第二个组是([^)]+) ,由$2引用。

使用这个正则表达式:

Regex rx = new Regex(@"\[(?<title>[^]]+)\]\((?<url>[^)]+)\)");

然后你可以迭代所有匹配并得到两个值:

foreach(Match match in rx.Matches(yourString))
{
    string title = match.Groups["title"].Value;
    string url = match.Groups["url"].Value;
    string anchorTag = string.Format("<a href=\"{0}\">{1}</a>", url, title);
    DoSomething(anchorTag);
}

使用这个正则表达式:

^\[([^\]]+)\]\(([^\)]+)\)$

使用此替换字符串:

<href="$2">$1</a> 

美元符号表示捕获组(这些是由打开/关闭括号括起来的项目),并将提取这些组捕获的值。

它看起来像这样的帮助:

'@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@'

发现于: http//snipplr.com/view/36992/improvement-of-url-interpretation-with-regex/

暂无
暂无

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

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