gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:04 25 4
gpt4 key购买 nike

我在我的项目中将其作为单元测试运行

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

还有你的其他表情。您需要 () 将要提取为组的部分括起来。

关于Java 正则表达式错误 - 没有第 1 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com