views:

120

answers:

2

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#?

A: 

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.

David Zaslavsky
+1  A: 

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.

VonC