G D G D - 1 year ago 39
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:


The catch here is the parameter with name
, 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
, while also being able to specify what is on the left hand side. For instance, I may want only
params, or I may want only
params. Each one of these will be a seperate regex. For instance, the
regex will be separate from the
regex. I am very new to working with regex, and I can't get the results no matter what I seem to do.

Answer Source

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.