本文介绍了Java正则表达式错误 - 无组1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的项目中将其作为UnitTest运行
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));
}
}
但是我有一个错误 IndexOutOfBoundsException:没有组1
我知道这与 m.group(1)
有关,但是出了什么问题?在控制台中,我也从 m.find()
中看到 true
。我搜索了如何使用正则表达式,但它显示了这样做。
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.
这篇关于Java正则表达式错误 - 无组1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!