1
当我知道格式将始终为${INT1...INT2}
(例如,)时,期望从字符串得到2个整数的最简单的简洁方法是什么? ?。“你好${123...456}
将提取123,456
当我知道格式将始终为${INT1...INT2}
(例如,)时,期望从字符串得到2个整数的最简单的简洁方法是什么? ?。“你好${123...456}
将提取123,456
我会去与一个Pattern
团体和反向引用
下面是一个例子:
String input = "Hello ${123...456}, bye ${789...101112}";
// | escaped "$"
// | | escaped "{"
// | | | first group (any number of digits)
// | | | | 3 escaped dots
// | | | | | second group (same as 1st)
// | | | | | | escaped "}"
Pattern p = Pattern.compile("\\$\\{(\\d+)\\.{3}(\\d+)\\}");
Matcher m = p.matcher(input);
// iterating over matcher's find for multiple matches
while (m.find()) {
System.out.println("Found...");
System.out.println("\t" + m.group(1));
System.out.println("\t" + m.group(2));
}
输出
Found...
123
456
Found...
789
101112
final String string = "${123...456}";
final String firstPart = string.substring(string.indexOf("${") + "${".length(), string.indexOf("..."));
final String secondPart = string.substring(string.indexOf("...") + "...".length(), string.indexOf("}"));
final Integer integer = Integer.valueOf(firstPart.concat(secondPart));
是th e点是任意字符的占位符?你的整数总是三位数? –
首先用3个点分割它,得到一个字符串数组,例如t。 num1 = t [0] .split(“$ {”)[1],num2 = t [1] .substring(0,t [1] .length() - 1) –