Stanley Shilov

Java Mad Libs function

September 26th, 2009

This 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.

© 2012 Stanley Shilov   |   Blog   |   Contact

divide et impera

Stanley Shilov