urg*_*as9 4 java string string.format string-formatting formatter
在 Java 程序中,我使用的是Formatter.format()从服务器获取的带函数的字符串。我不能确定String要格式化的有占位符或有效数量的占位符。如果它String不符合预期,我想抛出一个异常 - 或者以某种方式记录它。
在这一点上,我不在乎什么类型的占位符是 ( String, Integer,...),我只想获得每个字符串的预期参数数量。
实现这一目标的最简单方法是什么?一种方法可能是使用正则表达式,但我在想是否有更方便的东西 - 例如内置函数。
这里有些例子:
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
Run Code Online (Sandbox Code Playgroud)
编辑:如果提供的参数不足,Formatter.format() 会引发异常。有可能我得到一个没有占位符的字符串。在这种情况下,即使我提供参数(将被省略),也不会抛出异常(即使我想抛出一个),只会返回该字符串值。我需要向服务器报告错误。
您可以使用定义占位符格式的正则表达式来计算字符串中的匹配总数。
// %[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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
%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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1614 次 |
| 最近记录: |