-1

I'm trying to parse content of a string to see if the string includes urls, to convert the full string to html, to make the string clickable.

I'm not sure if there is a smarter way of doing this, but I started trying creating a parser with the Split method for strings, or Regex.Split in C#. But I can't find a good way of doing it.

(It is a ASP.NET MVC application, so perhaps there is some smarter way of doing this)

I want to ex. convert the string;

"Customer office is responsible for this. Contact info can be found {link}{www.customerservice.com}{here!}{link} More info can be found {link}{www.customerservice.com/moreinfo}{here!}{link}"

Into

"Customer office is responsible for this. Contact info can be found <a href=www.customerservice.com>here!</a> More info can be found <a href=www.customerservice.com/moreinfo>here!</a>"

i.e.

{link}{url}{text}{link} --> <a href=url>text</a>

Anyone have a good suggestion? I can also change the way the input string is formatted.

Mark Shevchenko
  • 7,297
  • 1
  • 21
  • 25
user2590683
  • 153
  • 1
  • 1
  • 9

4 Answers4

1

You can use the following to match:

{link}{([^}]*)}{([^}]*)}{link}

And replace with:

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

See DEMO

Explanation:

  • {link} match {link} literally
  • {([^}]*)} match all characters except } in capturing group 1 (for url)
  • {([^}]*)} match all characters except } in capturing group 2 (for value)
  • {link} match {link} literally again
karthik manchala
  • 13,025
  • 1
  • 27
  • 54
0

you can use regex as

{link}{(.*?)}{(.*?)}{link}

and substution as

<a href=\1>\2</a>

Regex

Rahul
  • 3,401
  • 3
  • 13
  • 27
0

For your simple link format {link}{url}{text} you can use simple Regex.Replace:

Regex.Replace(input, @"\{link\}\{([^}]*)\}\{([^}]*)\}", @"<a href=""$1"">$2</a>");
Mark Shevchenko
  • 7,297
  • 1
  • 21
  • 25
0

Also this non-regex idea may help

var input = "Customer office is responsible for this. Contact info can be found {link}{www.customerservice.com}{here!}{link} More info can be found {link}{www.customerservice.com/moreinfo}{here!}{link}";

var output = input.Replace("{link}{", "<a href=")
                  .Replace("}{link}", "</a>")
                  .Replace("}{", ">");
Hossein Narimani Rad
  • 27,798
  • 16
  • 81
  • 109