0

I am new to Java language, I need to extract all variables which are defined within ${} the given string. This string can be of any length and it can contain any number of variables.

For example:

This is a${VARIABLE1} sample string ${VARIABLE2} to process data ${VARIABLE3}

After processing I just want to get whichever is defined within ${} - It means I should be getting VARIABLE1,VARIABLE2, VARIABLE3

Can someone please help me code for it.

Thanks

Praveen Kumar
  • 27
  • 1
  • 4
  • 3
    Does this answer your question? [Using Regular Expressions to Extract a Value in Java](https://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java) with the appropriate regex such as `"\\$\\{[^}]+\}"` – knittl Oct 13 '22 at 08:21

1 Answers1

1

Using Java 8:

You can try the below approach for extracting out the values enclosed with ${}

Here,

  1. I have first split the string based on $ and then filter the values which contains "{" and "}".
  2. 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]
GD07
  • 1,117
  • 1
  • 7
  • 9
  • Thanks for your response. If you can provide example code using regex that would be great. The reason why I am saying is, given string may contain some other set of { and }. so check for string containg { and } might fail. and this way i will have to put some extra logic. instead if we can do this using regex then it would be great. – Praveen Kumar Oct 13 '22 at 15:17
  • @PraveenKumar I got your point, I will try to solve by using regex as well. But this solution will also work perfectly as i am considering only cases enclosed in `@{}` and also handled the empty cases enclosed in `@{}`. – GD07 Oct 13 '22 at 15:35