繁体   English   中英

如何在Java正则表达式中计算字符串中括号的数量

[英]how do I count the number of brackets in a string in a Java regex

因此,我试图通过使用正则表达式来计算字符串中括号(例如,方括号)的数量。 我在匹配器类中找到了此方法“ 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。

很迷茫。

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

以下内容是否太实用?

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

(当然,这假设您要搜索一个真正的RE,而不仅仅是一个括号。否则,只需使用s.replace(")","")

您并未真正开始搜索,这是发生异常的原因。

Matcher.groupCount()返回Pattern中的组数,而不是结果。

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

您可以参考此页面

我这样更改您的代码,

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
)

请使用以下代码。

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

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

int totalCount = count1+count2;

StringUtils存在于common-lang库中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM