【问题标题】:how do I count the number of brackets in a string in a Java regex如何计算Java正则表达式中字符串中括号的数量
【发布时间】:2011-12-06 08:37:50
【问题描述】:

所以我试图通过使用正则表达式来计算字符串中括号(例如右括号)的数量。我在匹配器类上找到了这个方法“groupCount”。所以我认为这可以帮助我。

groupCount 在 JavaDoc 中说“任何小于或等于此方法返回值的非负整数都保证是此匹配器的有效组索引。”所以我想那句话

m.group(m.groupCount());

应该总是有效的。错了……

这是我写的一些测试代码:

public class TestJavaBracketPattern {

    public static void main(String[] args) {
        Matcher m = Pattern.compile("(\\))").matcher(")");
        System.out.println(m.group(m.groupCount()));
    }

}

现在我期望匹配一个右括号(在正则表达式中称为 \)并获得一个匹配项。正则表达式是 (\)) - 这应该匹配包含右括号符号的组。但它只是抛出一些异常(java.lang.IllegalStateException:未找到匹配项)。

接下来,我尝试在没有匹配的地方进行匹配:

public class TestJavaBracketPattern {

    public static void main(String[] args) {
        Matcher m = Pattern.compile("(\\))").matcher("(");
        System.out.println(m.group(m.groupCount()));
    }

}

我得到了同样的例外。事实上,在这两种情况下,我发现 groupCount 方法都返回 1。

很困惑。

【问题讨论】:

标签: java regex


【解决方案1】:

下面是不是太务实了?

@Test
void testCountBrackets() {
    String s = "Hello) how)are)you(";
    System.out.println( s.length() - s.replaceAll("\\)", "").length() ); // 3
}

(当然,这假设您要搜索比括号更复杂的真实RE。否则只需使用s.replace(")","")

【讨论】:

  • 其实,这是我一年来见过的最优雅的东西
  • 这不是失败...我尝试运行它,它每次都报告成功(不是失败)! ;-)
  • assertEquals(3, s.replaceAll("[^\\)]", "").length()); 更短。现在够了。回去工作:-)
【解决方案2】:

groupCount 返回模式中的组数,而不是匹配结果中的组数。

你将不得不做这样的事情;

Matcher m = Pattern.compile("(\\))").matcher("Hello) how)are)you(");
int count = 0;
while (m.find()) {
    count++;
}
System.err.format("Found %1$s matches\n", count);

【讨论】:

    【解决方案3】:

    你并没有真正开始搜索,这是发生异常的原因。

    Matcher.groupCount() 返回 Pattern 中有多少组,而不是结果。

    Matcher.group() 返回给定组在上一次匹配期间捕获的输入子序列。

    您可以参考this page

    我这样修改你的代码,

    public class TestJavaBracketPattern {
    
        public static void main(String[] args) {
           Matcher m = Pattern.compile("(\\))").matcher(")");
           if (m.find()) {           
             System.out.println(m.group(m.groupCount()));
           }
        }
    }
    

    添加m.find(),结果为:

    1
    )
    

    【讨论】:

      【解决方案4】:

      请使用以下代码。

      int count1 = StringUtils.countMatches("fi(n)d ( i)n ( the st)(ri)ng", "("); // 对于'('

      int count2 = StringUtils.countMatches("fi(n)d ( i)n ( the st)(ri)ng", ")"); // 对于')'

      int totalCount = count1+count2;
      

      StringUtils 存在于common-lang 库中。

      【讨论】:

        猜你喜欢
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多