Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Created July 30, 2021 01:37
Show Gist options
  • Save mattkenefick/8c07ab12c96c53cccf3eaa9a65f7a0d2 to your computer and use it in GitHub Desktop.
Save mattkenefick/8c07ab12c96c53cccf3eaa9a65f7a0d2 to your computer and use it in GitHub Desktop.
Regular Expressions: Markdown to HTML anchors
/ \[([^\]]+)\]\(([^\)]+)\) /
\[([^\]]+)\]
\[ Look for a literal left bracket, by escaping it
( Start a capture group to retrieve the contents
[^\]]+ Repeatedly find a character that isn't a closing bracket
) Close the capture group
\] Look for a literal right bracket, by escaping it
\(([^\)]+)\)
\( Look for a literal left parenthesis, by escaping it
( Start a capture group to retrieve the contents
[^\)]+ Repeatedly find something that isn't a right parenthesis
) Close the capture group
\) Look for a literal right parenthesis, by escaping it
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "[I'm an inline-style link](https://www.google.com)";
string replacement = Regex.Replace(input, @"\[([^\]]+)\]\(([^\)]+)\)", m => string.Format(
"<a href=\"{1}\">{0}</a>",
m.Groups[1].Value,
m.Groups[2].Value
));
Console.WriteLine(replacement);
}
}
var markdown = "[I'm an inline-style link](https://www.google.com)";
var html = markdown.replace(/\[([^\]]+)\]\(([^\)]+)\)/, '<a href="$2">$1</a>');
alert(html);
<?PHP
$markdown = "[I'm an inline-style link](https://www.google.com)";
$html = preg_replace('/\[([^\]]+)\]\(([^\)]+)\)/', '<a href="\2">\1</a>', $markdown);
echo $html;
/\[([^\]]+)\]\(([^\)]+)\)/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment