遍历正则表达式查找

Anu*_*jKu 8 java regex

输入->输入!RC + Calc!R[1]C[1]

在输出中,我想对这些进行操作:

RC 和 R[1]C[1]

我的尝试:

私有静态无效 findMatch(字符串公式){
         匹配器 m = Pattern.compile("\\W(R(\\[(.+?)\\])?C(\\[(.+?)\\]))")
         .matcher(公式);
        // 匹配器 m = Pattern.compile(
        // "\\W(R(\\[(.+?)\\])?C) | \\W(R(\\[(.+?)\\])?C(\\[( .+?)\\]))")
        // .matcher(公式);
        for (; m.find(); m.reset(formula)) {
            System.out.println(m.group(3));
        }

    }

它不会寻找第二个模式,也不会进入无限循环。

这有什么问题?

And*_*ark 7

请尝试以下操作:

String formula = "Input!RC + Calc!R[1]C[1]";
Matcher m = Pattern.compile("\\W(R(\\[(.+?)\\])?C(\\[(.+?)\\])?)").matcher(formula);
while (m.find()) {
    System.out.println(m.group(1));
}
Run Code Online (Sandbox Code Playgroud)

输出:

String formula = "Input!RC + Calc!R[1]C[1]";
Matcher m = Pattern.compile("\\W(R(\\[(.+?)\\])?C(\\[(.+?)\\])?)").matcher(formula);
while (m.find()) {
    System.out.println(m.group(1));
}
Run Code Online (Sandbox Code Playgroud)

这里的主要变化是循环的工作方式,我上面提到的是迭代模式匹配的典型方法。我也在打印m.group(1)而不是m.group(3)因为它是第一个包含除 之外的整个匹配项的组,!我认为这是您想要的。

此处对正则表达式的唯一更改是?在第二(\\[(.+?)\\])组之后添加以使其可选。