You actually get an IllegalStateException
public class RegexDemo { public static void main(String[] args) { Pattern p = Pattern.compile(".*\\\"(.*)\\\".*"); Matcher m = p.matcher("your \"string\" here"); System.out.println(m.group(1)); } }
He gives:
Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Matcher.java:485) at RegexDemo.main(RegexDemo.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Before using group() you need to call find() or matches() .
A simple test, for example:
public class RegexTest { @Test(expected = IllegalStateException.class) public void testIllegalState() { String string = new String("your \"string\" here"); Pattern pattern = Pattern.compile(".*\\\"(.*)\\\".*"); Matcher matcher = pattern.matcher(string); System.out.println(matcher.group(1)); } @Test public void testLegalState() { String string = new String("your \"string\" here"); Pattern pattern = Pattern.compile(".*\\\"(.*)\\\".*"); Matcher matcher = pattern.matcher(string); if(matcher.find()) { System.out.println(matcher.group(1)); } } }
Aleksey Bykov
source share