Skip to content

Instantly share code, notes, and snippets.

@aembleton
Created March 17, 2011 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aembleton/875373 to your computer and use it in GitHub Desktop.
Save aembleton/875373 to your computer and use it in GitHub Desktop.
Matches regular expressions in the haystack. Any matched strings are returned in a list.
package util;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
/**
* Matches regular expressions in the haystack. Any matched strings are
* returned in a list.
*
* @param regex
* The regular expression with which to match
* @param haystack
* The string from which to find matches
* @return A {@link List} of {@link String} objects where every String
* matches the regex and they are all in the haystack
*/
public static List<String> getMatches(String regex, String haystack) {
if (regex == null || regex.equals("")) {
throw new IllegalArgumentException("regex cannot be null or empty.");
}
if (haystack == null || haystack.equals("")) {
throw new IllegalArgumentException("haystack cannot be null or empty.");
}
List<String> result = new LinkedList<String>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(haystack);
while (matcher.find()) {
result.add(haystack.substring(matcher.start(), matcher.end()));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment