Created
March 17, 2011 23:39
-
-
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.
This file contains hidden or 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
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