Home » Java » How to split query string q value in java 8 – Stack Overflow

How to split query string q value in java 8 – Stack Overflow

Posted by: admin February 20, 2020 Leave a comment

Questions:

I would like to get myInfo value which tests from the below-given string test.

public class Test {
    public static void main(String[] args) {

        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";
    }
}

Expected output:

test

How to split and get the required value in Java 8?

Answers:

One of the possible solutions for this task will be using Pattern class.

Here is code demo:

public class RegexDemo {
    public static void main(String[] args) {
        String test = "{q=code=in=(100,110,120,100);product=in=(393,393);ID==33323323, myInfo==test, offset=0, limit=200}";

        printMyInfoValue(test);
    }

    private static void printMyInfoValue(String test) {
        Pattern pattern = Pattern.compile("\s+myInfo==(\w+)");
        Matcher matcher = pattern.matcher(test);

        if (matcher.find()) {
            System.out.printf("My Info value: %s\n", matcher.group(1).trim());
        }
    }
}

Output:

test

At regex, we are checking if myInfo is presented in a text. If yes just group the results with parenthesis ().
For group with index 0 group(0) we will have full regex value:

myInfo==test

For 1 group group(1) only value:

test

It is exactly what we are looking for.
If no myInfo key is presented for input text -> no printing result.
Java 8 isn’t the best choice in this case to my opinion.