Question

I need to implement something similar to wikilinks on my site. The user is entering plain text and will enter [[asdf]] wherever there is an internal link. Only the first five examples are really applicable in the implementation I need.

Would you use regex, what expression would do this? Is there a library out there somewhere that already does this in C#?

Was it helpful?

Solution

On the pure regexp side, the expression would rather be:

\[\[([^\]\|\r\n]+?)\|([^\]\|\r\n]+?)\]\]([^\] ]\S*)
\[\[([^\]\|\r\n]+?)\]\]([^\] ]\S*)

By replacing the (.+?) suggested by David with ([^\]\|\r\n]+?), you ensure to only capture legitimate wiki links texts, without closing square brackets or newline characters.

([^\] ]\S+) at the end ensures the wiki link expression is not followed by a closing square bracket either.

I am note sure if there is C# libraries already implementing this kind of detection.

However, to make that kind of detection really full-proof with regexp, you should use the pushdown automaton present in the C# regexp engine, as illustrated here.

OTHER TIPS

I don't know if there are existing libraries to do this, but if it were me I'd probably just use regexes:

  • match \[\[(.+?)\|(.+?)\]\](\S+) and replace with <a href="\2">\1\3</a>
  • match \[\[(.+?)\]\](\S+) and replace with <a href="\1">\1\2</a>

Or something like that, anyway.

Although this is an old question and already answered, I thought I'd add this as an addendum for anyone else coming along. The existing two answers do all the real work and got me 90% there, but here is the last bit for anyone looking for code to get straight on with trying:

string html = "Some text with a wiki style [[page2.html|link]]";
html = Regex.Replace(html, @"\[\[([^\]\|\r\n]+?)\|([^\]\|\r\n]+?)\]\]([^\] ]\S*)", @"<a href=""$1"">$2$3</a>");
html = Regex.Replace(html, @"\[\[([^\]\|\r\n]+?)\]\]([^\] ]\S*)", @"<a href=""$1"">$1$2</a>");

The only change to the actual regex is I think the original answer had the replacement parts the wrong way around, so the href was set to the display text and the link was shown on the page. I've therefore swapped them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top