G D G D - 2 months ago 6
Java Question

Match non null words preceded by certain strings only

I've got a request parameter string that will always come to my server like so:

str1=wordA&str2=wordB&desc3=&int=0
etc.

The catch here is the parameter with name
desc3
, which may or may not have data accompanied with it, as I've shown here, with no data. What I'm trying to do is use regex to extract strings that match the right hand side of
str1=word
, while also being able to specify what is on the left hand side. For instance, I may want only
str1
params, or I may want only
desc
params. Each one of these will be a seperate regex. For instance, the
str1
regex will be separate from the
desc3
regex. I am very new to working with regex, and I can't get the results no matter what I seem to do.

Answer

Sometimes a regex isn't the correct way to do it. I would try a string split approach:

    String testString = "str1=wordA&str2=wordB&desc3=&int=0";
    Map<String, String> mapOfParams = Arrays.stream(testString.split("&"))
            .collect(Collectors.toMap(s -> s.split("=")[0],
                                      s -> s.split("=").length > 1 ? s.split("=")[1] : ""));

This will give you a Map with empty values as empty strings.