模式匹配问题

jen*_*gar 1 java regex

所以我有一个看起来像这样的函数:

private int getNumber(String commandChunk)
    {
        Pattern pattern = Pattern.compile("R(\\d+)");
        Matcher m = pattern.matcher(commandChunk);
        return Integer.parseInt(m.group(1));
    }
Run Code Online (Sandbox Code Playgroud)

用"R0"调用它.我希望它返回int:0,但我在return语句中得到一个非法的状态异常.我究竟做错了什么?我不明白为什么我不能说int myNum = getNumber("R0")最终myNum = 0.

Rei*_*eus 5

group抛出一个IllegalStateException如果没有前面的任何一个matchesfind.在调用matches之前调用group,以使表达式与完成匹配String:

class NumberTest {
    final static Pattern pattern = Pattern.compile("R(\\d+)");

    public static void main(String[] args) {
        System.out.println(new NumberTest().getNumber("R0"));
    }

    private int getNumber(String commandChunk) {
        Matcher m = pattern.matcher(commandChunk);
        if (m.matches()) {
            return Integer.parseInt(m.group(1));
        } else {
            return -1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)