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.

JavaScript

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:

JavaScript

Output:

JavaScript

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