从Java中的Comment部分读取值

我将注释作为输入,我需要从中检索值。我怎样才能做到这一点?

输入Comment =“ =”服务维护,已与我联系有关安全气囊的召回。我何时可以预定?制造:Nissan \ n型号:X-TRAIL \ n系列:T324 \ n描述:X-TRAIL Desc \ nBodyType:4X4 \ n”;

我需要从此输入中检索Make,Model,Series,Description,BodyType。

注意:如果不存在值,则应为空。

           */*Reading Make value from Comment Section*/*
            String Makevalue=comments.contains("Make :") ? comments.substring(comments.lastIndexOf("Make :"),comments.indexOf("Model :")):"";
            Make=Makevalue.length()>0?Makevalue.substring(Makevalue.lastIndexOf(":")+ 1):"";
            System.out.println(" Make is ::::::: " + Make);
            /*Reading Model value from Comment Section*/
            String Modelvalue=comments.contains("Model :") ? comments.substring(comments.lastIndexOf("Model :"),comments.indexOf("Series :")):"";
            Model=Modelvalue.length()>0?Modelvalue.substring(Modelvalue.lastIndexOf(":")+ 1):"";
            System.out.println(" Model is ::::::: " + Model);
            /*Reading Description value from Comment Section*/
            String Descvalue=comments.contains("Description :") ? comments.substring(comments.lastIndexOf("Description :"),comments.indexOf("BodyType :")):"";
            Description=Descvalue.length()>0?Descvalue.substring(Descvalue.lastIndexOf(":")+ 1):"";
            System.out.println(" Description is ::::::: " + Description);

当所有值以相同顺序(Make,Model,Series,Description,BodyType)存在时,此示例代码有效

有什么有效的方法可以做到这一点吗?

评论
  • 墨小沫
    墨小沫 回复
    1. You can first split based on ? which will give me input parameters.
    2. Then split based on \n this will give me array of parameters
    3. Split based on : to get ket and value pair.
      Note This is very specific solution for given comment, anything changes in this will might broke the code .

      String comment = "service-maintenance,I have been contacted about an airbag recall. When can I book?Make : Nissan\nModel : X-TRAIL\nSeries : T324\nDescription : X-TRAIL Desc\nBodyType : 4X4\n";
      
      String[] arr = comment.split("\\?");
      String[] newArr =  arr[1].split("\n");
      
      for (String string : newArr) {
          String[] arrValue = string.split(":");
          System.out.println("key: "+ arrValue[0] +" value: "+ arrValue[1]);
      
      }