在一些正则表达式中获取字符串的值

时间:2014-12-16 09:34:28

标签: java regex

我有这样的代码:

String s1 = "((${adapterKind=VMWARE, resourceKind=VirtualMachine, metric=disk|usage_average}*${this, metric=summary|oversizedVMCount})+${this, metric=summary|poweredOffVMCount})";
//Some code

I want output inside

String[] s2 = {${adapterKind=VMWARE, resourceKind=VirtualMachine, metric=disk|usage_average}, ${this, metric=summary|oversizedVMCount}, ${this, metric=summary|poweredOffVMCount}};

基本上我想获得所有与" $ {...}"一起使用的值。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

String s1 = "((${adapterKind=VMWARE, resourceKind=VirtualMachine, metric=disk|usage_average}*${this, metric=summary|oversizedVMCount})+${this, metric=summary|poweredOffVMCount})";
Pattern p = Pattern.compile("\\$\\{[^}]*\\}");
Matcher m = p.matcher(s1);
while(m.find())
    //here you have the captured texts, 
    //you can put into array/collection as you like
    System.out.println(m.group());

此输出:

${adapterKind=VMWARE, resourceKind=VirtualMachine, metric=disk|usage_average}
${this, metric=summary|oversizedVMCount}
${this, metric=summary|poweredOffVMCount}

答案 1 :(得分:0)

您可能需要查看java.util.regex.Matcher#find()方法。

This question has a solution