Java正则表达式错误 – 没有组1

我在我的项目中将其作为UnitTest运行

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)); } } 

但我得到一个错误IndexOutOfBoundsException: No group 1我知道这与m.group(1) ,但是有什么问题? 在控制台中我也从m.find()看到了true 。 我搜索了如何使用正则表达式,但它表明这样做。

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

没有定义组,因此该表达式匹配,但您无法提取组。 你可能想要这样做:

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

还为你的其他表达。 您需要()将要提取的部分包含在组中。