Using Java 8:
You can try the below approach for extracting out the values enclosed with ${}
Here,
- I have first split the string based on
$
and then filter the values which contains "{"
and "}"
.
- Then I have iterated over the list and find the starting and ending index of that string and using these indexes, prepared the substring and added it to the list.
Note: In the final list, ignoring the data like ${}, ${ }, and so on, which contains no variable enclosing ${}
Code:
public class Test {
public static void main(String[] args) {
String s = "This is a ${VARIABLE1} sample string ${VARIABLE2} to process data ${VARIABLE3} ${TEST} ${ } ${}";
List<String> output = new ArrayList<>();
Stream.of(s.split("\\$")).filter(x -> x.contains("{")
&& x.contains("}")).forEach(x -> {
int i1= x.indexOf("{");
int i2 = x.indexOf("}");
String ss = x.substring(i1+1,i2);
if(!ss.trim().equals("")){
output.add(ss);
}
});
System.out.println(output);
}
}
Output:
[VARIABLE1, VARIABLE2, VARIABLE3, TEST]