正则表达式匹配${123…456}并在Java中提取2个数字? 1 年,4 月 Questions & Answers 135 当我知道一个字符串的格式总是${INT1...INT2}例如,“Hello${123...456}将提取123,456时,从字符串中期望2个整数的最简单简洁的方法是什么
# 1 楼答案 我会使用带有组和反向引用的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
# 2 楼答案 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));
# 1 楼答案
我会使用带有组和反向引用的
Pattern
下面是一个例子:
输出
# 2 楼答案