简体   繁体   English

计算正则表达式匹配

[英]Counting regex matches

I need to count the matches that regex found to declare an array. 我需要计算正则表达式声明一个数组的匹配。 I tried it with .groupCount() but that doesn't seem to be the right thing^^ My code: 我用.groupCount()尝试过,但这似乎不是正确的事^^我的代码:

Pattern p2 = Pattern.compile("<char>(.*?)</char>");
response = response.replaceAll("[\\r\\n]+",  "");
Matcher m2 = p2.matcher(response);

String[] chars = new String[m2.groupCount()];

It should find 2, but says 1. Can anyone help? 它应该找到2,但是说1.有人可以帮忙吗?

groupCount() counts the capturing groups in the Pattern , not number of matches. groupCount()计算中的捕获组Pattern ,不匹配的数量。

The easiest way, I would think, would be to use a resizable List ( ArrayList for instance) to store your matches, and then convert it to an array if you need to ( ArrayList.toArray() ) 我认为,最简单的方法是使用可调整大小的List (例如ArrayList )来存储匹配项,然后在需要时将其转换为数组( ArrayList.toArray()

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

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