是否有一个班轮来代替 while 循环?
String formatSpecifier = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
Pattern pattern = Pattern.compile(formatSpecifier);
Matcher matcher = pattern.matcher("hello %s my name is %s");
// CAN BELOW BE REPLACED WITH A ONE LINER?
int counter = 0;
while (matcher.find()) {
counter++;
}
Run Code Online (Sandbox Code Playgroud)
是:将任何出现的字符替换为既不在模式中也不在要匹配的字符串中的字符,然后计算该字符出现的次数。这里我选择X,为了示例简单。您应该使用不常用的字符(例如,请参阅 UTF-8 特殊字符)。
final int counter = pattern.matcher("hello %s my name is %s").replaceAll("X").replaceAll("[^X]", "").length();
Run Code Online (Sandbox Code Playgroud)
在您的示例中,计数器的计算值是 2。
| 归档时间: |
|
| 查看次数: |
3202 次 |
| 最近记录: |