简体   繁体   中英

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:

  • firstName: ar ,lastName:smith,
  • firstName: ar ,lastName:smith,addedAt<2020-03-15,
  • firstName: ar ,lastName:smith,phone:123456789,
  • firstName: ar ,lastName:smith,email:email@email.com,

every key-value must ends with comma(,)

I have a regex like that:

  • Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\p{Punct}?)((\\w+?)|((\\d{4}-\\d{2}-\\d{2})?+))(\\p{Punct}?),");
  • Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\p{Punct}?)[a-zA-Z](\\p{Punct}?),");

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

Please about some advices how to properly construct Pattern.

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@email.com,"
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM