Java Mad Libs function
Posted on Saturday, September 26th, 2009 under CodingThis madlibs Java function finds keyword combinations contained in {curly brackets} and randomly selects one of the keywords.
Ex: This {string|sentence|bit of text} will be different every time you {run|execute} the {function|method|Mad Lib function|madlib method}
// Madlib function:
public static String madlib(String content){
Pattern regex = Pattern.compile("\\{(.*?)\\}");
Matcher matches = regex.matcher(content);
String[] madlibArray = null;
while(matches.find()){
madlibArray = matches.group(1).split("\\|");
content = content.replace("{" + matches.group(1) + "}", madlibArray[(int) (Math.random() * madlibArray.length)]);
}
return content;
}
If you have any suggestions on how to improve this method, leave a comment.
Tags: content generation, java, madlib
You can leave a response, or trackback from your own site.Leave a Reply
« Ubiquity Rapidshare ExtensionHow to build Firefox 3.5+ with JSSH on Ubuntu 9.10 64bit »


Thanks for posting this, I’ve been looking for a simple way to do this.
Would you advise against running this on very large blocks of text?