简体   繁体   中英

Retrieve data from a String

I have this String which is coming from form:

   String tmp = "Reason: decision=deny&denyReason=1&denyReasonSubcategory=PoorQuality&subCategoryComments=testsubCategoryComments=subCategoryComments=denyReasonSubcategory=ReviewAgainsubCategoryComments=hellosubCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryCommen=&subCategoryComments=&subCategoryComments=&subCategoryComments=&subCategoryComments=";

From the above string I need to retrieve:

 denyReason=1
 denyReasonSubcategory=PoorQuality  subCategoryComments=test
 denyReasonSubcategory=ReviewAgain   subCategoryComments=hello

I need to save them as below:

deny Reason in an array, so i can find corresponding value.

Rest as: Poor Quality :test; Review Again:hello

I have tried following:

          for (String word : tmp.split("\\&+")){
           if (word.contains("declineReason")){
                System.out.println(word.indexOf("declineReason"));
            // coming as 0
           }
          if (word.contains("declineReasonSubcategory")){
                System.out.println("helloo");
          }
          if (word.contains("subCategoryComments")){
                System.out.println("hii");
          } 
         }
        }

Honestly, it's been long since I work on string like this and just little lost on how to get the data.

I would use a Scanner to extract the values.
One scanner to extract the pairs. Another scanner to extract the values of the pair.

See:

import java.util.*;
public class Main{
    public static void main(String[] args) {
      String tmp = "Reason: decision=deny&denyReason=1&denyReasonSubcategory=PoorQuality&subCategoryComments=testsubCategory";
      Scanner s = new Scanner(tmp).useDelimiter("\\&");
      while(s.hasNext()){
         Scanner s2 = new Scanner(s.next()).useDelimiter("=");
         System.out.println(s2.next() + ":" + s2.next());
      }
    }
}

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