Skip to content
Advertisement

Fetching to substring before operator from a dynamic string

I have a string like “name = mita and salary> 10000” . Out of which I need to get only name and salary attribute.I am going to have dynamic string on which i need the attribute before operator only. Like here I need to fetch name and salary attribute which r before = and > operator. I can have multiple condition of same type in the string. I can anyone please feasible way to fetch string before operator in Java8 Please find the example strings and expected output as below:

String str ="name = 'mita' and salary> 10000" ;
//output expected name, salary

String str1 = "role!= 'software engineer' and salary < 50000 and surname='mitra'";
// output expected role,salary,surname

String str2 = "name= 'dev' and role!= 'software engineer' and salary < 50000 and surname='mitra'";
// output expected name,role,salary,surname

Advertisement

Answer

You can make use of split method of String class and Regex :

String abc = "name = 'mita' and salary> 10000";
List<String> collect = Stream.of(abc.split("and|or"))
                .map(String::trim)
                .map(str -> str.split("[^a-zA-Z0-9']")[0])
                .collect(Collectors.toList());
System.out.println(collect);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement