Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex Error - No group 1

I ran this as a UnitTest in my project

public class RadioTest {

    private static Pattern tier;
    private static Pattern frequency;
    private static Pattern state;

    static {
        tier = Pattern.compile("Tier: \\d");
        frequency = Pattern.compile("Frequency: \\d{3}");
        state = Pattern.compile("State: (OFF|ON)");
    }

    @Test
    public void test() {
        String title = "Tier: 2";
        String title2 = "Frequency: 135";
        String title3 = "State: ON";

        assertTrue(tier.matcher(title).matches());
        assertTrue(frequency.matcher(title2).matches());
        assertTrue(state.matcher(title3).matches());

        Matcher m = tier.matcher(title);

        System.out.println(m.find());
        System.out.println(m.group(1));
    }

}

But I got an error IndexOutOfBoundsException: No group 1 I know this has to do with m.group(1), but what's wrong? in the console I also see true from m.find(). I searched how to use regular expressions but it showed to do that.

like image 620
Pocketkid2 Avatar asked Aug 29 '15 01:08

Pocketkid2


1 Answers

Pattern.compile("Tier: \\d");

does not define a group so this expression matches but you can't extract a group. You'll probably want to do it like:

Pattern.compile("Tier: (\\d)");

Also for your other expressions. You'll need to () enclose parts that you want to extract as group.

like image 62
zapl Avatar answered Sep 28 '22 11:09

zapl