Skip to content
Advertisement

How can I get a special part in a string in Java? [closed]

I have to read commands from a file I have and take necessary actions according to each command. I was able to find out the process of reading from the file and what the command is, but I am having trouble transferring the specific information contained in the command to the program. As an example, the line read is as follows

Add id:12 name:"Sandik" singer:"Muslum Gurses" year:2009 count:5 price:20

I have separated this reading line in each space as u can see in below.

 Scanner scan = new Scanner(new File(args[0]));
 while (scan.hasNextLine()) {
      String data = scan.nextLine();
      String[] readedCommand = data.split(" ");

After this operation, readedCommands[0] gives me the read command. For the above example, readedCommands[0] = "Add"

After this step, I need to extract the information from the rest of the command, but I have no idea how to extract information such as id, name, singer. I will be grateful if you could help me. Thank you in advance.

Advertisement

Answer

You can do it by splitting the string twice:

  1. Split the given string, using the regex, s(?=w+:)
  2. Then iterate the resulting array from the index, 1 (because the string at index, 0 is the command) and split each element further on :

Demo:

public class Main {
    public static void main(String[] args) {
        String data = "Add id:15 singer:"Tarkan" name:"Adimi Kalbine Yaz" year:2010 count:10 price:20";

        // First, split on whitespace
        String[] parts = data.split("\s(?=\w+:)");

        // The first element in the array is the command
        String command = parts[0];
        System.out.println("Command: " + command);

        // Split the remaining elements on ':'
        for (int i = 1; i < parts.length; i++) {
            String[] keyVal = parts[i].split(":");
            if (keyVal.length == 2) {
                String key = keyVal[0];
                String value = keyVal[1];
                System.out.println("Key: " + key + ", Value: " + value);
            }
        }
    }
}

Output:

Command: Add
Key: id, Value: 15
Key: singer, Value: "Tarkan"
Key: name, Value: "Adimi Kalbine Yaz"
Key: year, Value: 2010
Key: count, Value: 10
Key: price, Value: 20

Explanation of the regex, s(?=w+:):

  1. s specifies whitespace.
  2. (?=w+:) specifies positive lookahead for one or more word character(s) followed by a :
Advertisement