嗨,我正在寻找一个会改变这种情况的正则表达式:
[check out this URL!](http://www.reallycoolURL.com)
Run Code Online (Sandbox Code Playgroud)
进入这个:
<a href="http://www.reallycoolURL.com">check out this URL</a>
Run Code Online (Sandbox Code Playgroud)
即用户可以使用我的格式输入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);
Run Code Online (Sandbox Code Playgroud)
请注意,我在模式中使用命名捕获组,这允许我${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);
Run Code Online (Sandbox Code Playgroud)
在这种情况下([^]]+),第一组$1是在替换模式中([^)]+)引用的,第二组是由替换模式引用的$2.