Adrian N.
Adrian N.

Reputation: 11

Java regular expression does not match the input

i have a problem with regex. I want to parse url with param which can contains one of the following:

every key-value must ends with comma(,)

I have a regex like that:

but it doesn't work with this above inputs except in the first case.

Please about some advices how to properly construct Pattern.

Upvotes: 0

Views: 62

Answers (1)

Batman
Batman

Reputation: 702

What you have is Comma delimited, colon separated key-value pairs. Unless some requirement forces you to use regex, which based on your comment it doesn't, split the value on the comma, then split the resulting array's values on the colon. What you'll end up with is an array of arrays with index 0 being the key, and index 1 being the value.

In the following example, using one of the values provided in OP, we split on the comma and loop through the resulting array splitting each index on the colon and adding it to a list each iteration.

String value= "firstName:ar,lastName:smith,email:[email protected],"
Map<String,String> keyValuePairs = new HashMap<>();
for (String kvp : value.split(",")) {
  String[] kvp = kvp.split(":");
  if (kvp.length != 2 || kvp[0].isEmpty()) {
    continue; //ignoring incorrectly formatted kvp
  }
  keyValuePairs.add(kvp[0], kvp[1]);
}
// do what you want with keyValuePairs;

Upvotes: 2

Related Questions