简体   繁体   English

Java 正则表达式与输入不匹配

[英]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:我想用可以包含以下之一的参数解析 url :

  • firstName: ar ,lastName:smith,名字: ar ,姓氏:史密斯,
  • firstName: ar ,lastName:smith,addedAt<2020-03-15,名字: ar ,姓氏:smith,添加时间<2020-03-15,
  • firstName: ar ,lastName:smith,phone:123456789,名字: ar ,姓氏:smith,电话:123456789,
  • firstName: ar ,lastName:smith,email:email@email.com,名字: ar ,姓氏: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.你最终会得到一个 arrays 数组,索引 0 是键,索引 1 是值。

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.在以下示例中,使用 OP 中提供的值之一,我们在逗号上拆分并循环遍历生成的数组,拆分冒号上的每个索引,并在每次迭代时将其添加到列表中。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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