Monday, November 02, 2009

Use regular expression to extract / parse a string into a collection of matched results recursively

Helped a person in doing an assignment and almost forgot a routine that I love in parsing a string into an ArrayList of matched results with a regular expression. Here it is:

Pattern p = Pattern.compile(...);
Matcher m = p.matcher(inputString);
List l = new ArrayList();
for (int i = 0; m.find(i); i = m.end()) {
l.add(m.group(index)); // depends on your regular expression grouping
}

No comments: