代码
String str = "首单${name}典可升级为高${phone}品无损音质";
Pattern pattern = Pattern.compile("(?<=\\$\\{)[^\\}]+")
Matcher m = pattern.matcher(str);
while(m.find()){
System.out.println(m.group());
}
输出
Connected to the target VM, address: '127.0.0.1:32539', transport: 'socket'
name
phone
Disconnected from the target VM, address: '127.0.0.1:32539', transport: 'socket'
解释
?<=x 匹配字符左边为x,但不包含x (不包含时,调用group()不会输出)
(?<=\\$\\{)x 表示x字符左边为`${`,但不匹配`${`字符
[^\\}]+ 表示x为非`}`字符的一个或多个字符
m.find() 查找下一个匹配的对象,默认从上一个位置查询,从指定位置查询使用find(int index)
m.group() 返回匹配到的字符