获取 Formatter.format() String 中占位符的数量 [英] Get number of placeholders in Formatter.format() String

查看:18
本文介绍了获取 Formatter.format() String 中占位符的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 程序中,我使用带有 Formatter.format() 函数,我从服务器获得.我不能确定要格式化的 String 是否具有占位符或有效数量的占位符.如果 String 不符合预期,我想抛出异常 - 或者以某种方式记录它.

In a Java program I am using a String with Formatter.format() function, which I get from server. I cannot be sure that String to be formatted has placeholder or a valid number of them. If it the String is not as expected I would like to throw an exception - or log it somehow.

此时我不在乎占位符是什么类型的 (String, Integer,...),我只想获得预期的数量每个字符串的参数.

At this point I don't care of what type of placeholders are (String, Integer,...), I would just like to get number of expected parameters for each String.

实现这一目标的最简单方法是什么?一种方法可能是使用正则表达式,但我在想是否有更方便的东西 - 例如内置函数.

What is the easiest way to achieve this? One way could be to use a regex, but I am thinking if there is something more convenient - a built in function for example.

以下是一些示例:

Example String | number of placeholders:
%d of %d          | 2
This is my %s     | 1
A simple content. | 0
This is 100%      | 0
Hi! My name is %s and I have %d dogs and a %d cats. | 3

如果提供的参数不足,Formatter.format() 会抛出异常.有可能我得到一个没有占位符的字符串.在这种情况下,即使我提供参数(将被省略),也不会抛出异常(即使我想抛出一个),只会返回该字符串值.我需要向服务器报告错误.

Formatter.format() throws an exception if there are not enough provided parameters. There is a possibility that I get a String without placeholders. In this case, even if I provide paramters (will be omitted), no exception will be thrown (eventhough I would like to throw one) only that String value will be returned. I need to report the error to server.

推荐答案

您可以使用定义占位符格式的正则表达式来计算字符串中匹配项的总数.

You could do it with a regular expression that defines the format of a placeholder to count the total amount of matches in your String.

// %[argument_index$][flags][width][.precision][t]conversion
String formatSpecifier
    = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
// The pattern that defines a placeholder
Pattern pattern = Pattern.compile(formatSpecifier);
// The String to test
String[] values = {
    "%d of %d",
    "This is my %s", 
    "A simple content.", 
    "This is 100%", "Hi! My name is %s and I have %d dogs and a %d cats."
};
// Iterate over the Strings to test
for (String value : values) {
    // Build the matcher for a given String
    Matcher matcher = pattern.matcher(value);
    // Count the total amount of matches in the String
    int counter = 0;
    while (matcher.find()) {
        counter++;
    }
    // Print the result
    System.out.printf("%s=%d%n", value, counter);
}

输出:

%d of %d=2
This is my %s=1
A simple content.=0
This is 100%=0
Hi! My name is %s and I have %d dogs and a %d cats.=3

这篇关于获取 Formatter.format() String 中占位符的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆