A couple of points:
The Javadoc for Matcher#group states:
IllegalStateException - If no match has yet been attempted, or if the previous match operation failed
That is, before using group, you must first use m.matches
(to match the entire sequence), or m.find
(to match a subsequence).
Secondly, you actually want m.group(1)
, since m.group(0)
is the whole pattern.
Actually, this isn't so important here since the regexp in question starts and ends with the capture parentheses, so that group(0) is the same string as group(1), but it would matter if your regexp looked like: "TITLE = (\".*\")"
Example code:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
@SuppressWarnings("serial")
public class MatcherTest {
@Test(expected = IllegalStateException.class)
public void testIllegalState() {
List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
System.out.println("Title : " + m.group(0));
}
@Test
public void testLegal() {
List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
if (m.find()) {
System.out.println("Title : " + m.group(1));
}
}
}