gpt4 book ai didi

java - 取消格式化字符串

转载 作者:行者123 更新时间:2023-12-01 11:28:50 25 4
gpt4 key购买 nike

我有一个简单的格式化字符串:

double d = 12.348678;
int i = 9876;
String s = "ABCD";
System.out.printf("%08.2f%5s%09d", d, s, i);

// %08.2f = '12.348678' -> '00012,35'
// %5s = 'ABCD' -> ' ABCD'
// %09d = '9876' -> '000009876'
// %08.2f%5s%09d = '00012,35 ABCD000009876'

当我知道模式:%08.2f%5s%09d和字符串:00012,35 ABCD000009876时:我可以以某种方式“取消格式化”这个字符串吗?

例如。预期结果类似于 3 个标记:'00012,35'、'ABCD'、'000009876'

最佳答案

这特定于您的模式。格式字符串的通用解析器(因为我们所说的取消格式化就是解析)看起来会有很大不同。

public class Unformat {

public static Integer getWidth(Pattern pattern, String format) {
Matcher matcher = pattern.matcher(format);
if (matcher.find()) {
return Integer.valueOf(matcher.group(1));
}
return null;
}

public static String getResult(Pattern p, String format, String formatted,
Integer start, Integer width) {
width = getWidth(p, format);
if (width != null) {
String result = formatted.substring(start, start + width);
start += width;
return result;
}
return null;
}

public static void main(String[] args) {
String format = "%08.2f%5s%09d";
String formatted = "00012.35 ABCD000009876";
String[] formats = format.split("%");

List<String> result = new ArrayList<String>();
Integer start = 0;
Integer width = 0;

for (int j = 1; j < formats.length; j++) {
if (formats[j].endsWith("f")) {
Pattern p = Pattern.compile(".*([0-9])+\\..*f");
result.add(getResult(p, formats[j], formatted, start, width));
} else if (formats[j].endsWith("s")) {
Pattern p = Pattern.compile("([0-9])s");
result.add(getResult(p, formats[j], formatted, start, width));
} else if (formats[j].endsWith("d")) {
Pattern p = Pattern.compile("([0-9])d");
result.add(getResult(p, formats[j], formatted, start, width));
}
}
System.out.println(result);
}

}

关于java - 取消格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30607856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com