Created
April 30, 2012 22:01
-
-
Save eclarke/2563046 to your computer and use it in GitHub Desktop.
modifying plain wikilinks in wikitext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String fixLinks(String src, Wiki target) { | |
// add a marker to all the links so we can iterate through them (except the ones that point to wikipedia) | |
String src2 = src.replaceAll("\\[\\[(?!(wikipedia))", "[[%"); | |
try { | |
while (src2.contains("[[%")) { | |
// extract the link text | |
int a = src2.indexOf("[[%")+3; // left inner bound | |
int b = src2.indexOf("]]", a); // right inner bound | |
String link = src2.substring(a, b); | |
// remove the label, if present | |
int pipe = link.indexOf('|'); | |
link = (pipe == -1) ? link : src2.substring(a, a+pipe); | |
// If the link does not exist (and is not a semantic wikilink or category), append 'wikipedia:' | |
if (!link.contains("::") && !link.contains(":") && !link.contains("Category:") && !target.exists(link)[0]) { | |
src2 = src2.substring(0, a-1) + "wikipedia:" + src2.substring(a); | |
// else if it's not a special link (like File: or en:), make it a semantic link | |
} else if (!link.contains(":")) { | |
src2 = src2.substring(0, a-1) + "is_associated_with::" + src2.substring(a); | |
// otherwise just remove the marker and move on | |
} else { | |
src2 = src2.substring(0, a-1) + src2.substring(a); | |
} | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return src; | |
} | |
return src2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment