Home > Enterprise >  Getting values between quotes from String - Java
Getting values between quotes from String - Java

Time:07-02

How can I get the value between quotes from below string:

Actually at end of each string below thing will attached with different parameter in Quotes:

Connect to Database to get data of student severity "low" priority "minor"

Connect to System API to get details severity "moderate" priority "medium"

The result must be:

severity = low
priority = minor

severity = moderate
priority = medium

CodePudding user response:

You can use regular expressions, like this:

String string = "Connect to Database to get data of student severity \"low\" priority \"minor\"";
Pattern pattern = Pattern.compile("severity \"(.*)\" priority \"(.*)\"");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
    String severity = matcher.group(1);
    String priority = matcher.group(2);
}

CodePudding user response:

Simple and core java:

         String word =  "Connect to Database to get data of student severity \"low\" priority \"minor\"";
         String [] wordArray = word.split(" ");
         
         String severity = "", priority = "";
         for(int i=0; i<wordArray.length; i  ) {
             if(wordArray[i].contains("severity")) {
                 severity = wordArray[i 1];
             }
             
             if(wordArray[i].contains("priority")) {
                 priority = wordArray[i 1];
             }
         }
         System.out.println(severity  " " priority);

CodePudding user response:

Most easy way to achieve that is by splitting the text at every " and taking the second and the fourth item:

String string = "Connect to Database to get data of student severity \"low\" priority \"minor\"";
String[] arr = string.split("\"");
String severity = arr[1];
String priority = arr[3];

Note that this way isn't secure against wrong input.

  •  Tags:  
  • java
  • Related