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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With