There is a line add J. Martin "A Song of Ice and Fire" and I need to break it into three parts. The first is add , the second автор and the third название книги .

Tell me what's best.

Found a way like this:

 Pattern pattern = Pattern.compile(" "); String[] values = pattern.split(value) 

but every time after that, to collect piece by piece is somehow not ok, what other ways are there? Thank!

    2 answers 2

    You can use groups for this. Groups are set in brackets, numbering from 1. The zero group returns the entire string.

      String value = "add J. Martin \"A Song of Ice and Fire\""; Pattern pattern = Pattern.compile("(\\w+)\\s+(.+)\\s+\"(.+)\""); Matcher matcher = pattern.matcher(value); if (matcher.matches()) { String command = matcher.group(1); String author = matcher.group(2); String book = matcher.group(3); } 
    • if not complicated please explain why after \\ s +, more precisely why? And it’s after the “J.” it finds the second space or does it go until it hits \ "?? thanks - Limpopo
    • @Limpopo in case there are several spaces or tabs. - Nail Samatov
    • This is to prevent spaces from falling into values ​​in groups - Nail Samatov

    It is possible so:

     String s = "add J. Martin \"A Song of Ice and Fire\""; String command = s.split(" ")[0]; String author = s.split("\"")[0].replaceFirst(command, "").trim(); String bookName = s.split("\"")[1]; 

    Provided that in the first part there will be no spaces, that is, instead of add there will not be two words for example, and that there are only quotes inside the line.

    • And if I enter from the keyboard, then the line will be with quotes? can this be seen only through debag? thank! - Limpopo