简体   繁体   中英

Java split string at spaces but keep tabs

I have a string "4612 CMP Computer Science Java II CMP110 A- 010" which is a course. I need to get the "Computer Science" and "Java II" bits. I think the easiest way to do it would be by splitting it into an array containing the tabs.

After the 4612 is a tab, as well in between Science and Java.

I want to split it to getting an array like this:

string[0] = 4612
string[1] = "    "
string[2] = CMP
string[3] = Computer
string[4] = Science
string[5] = "    "
string[6] = Java
string[7] = II
string[8] = CMP110 
string[9] = A-
string[10] = 010

Since the course string seems to have a well defined format, you could also use a Regular Expression to extract the relevant information, eg:

    final String course = "4612\tCMP Computer Science\tJava II CMP110  A-  010";
    final Pattern pattern = Pattern.compile("^\\d+\tCMP\\s+([^\t]+)\t(.+?)\\s+CMP.*$");
    final Matcher matcher = pattern.matcher(course);

    if (matcher.matches()) {
        System.out.println("Course name: " + matcher.group(1) + " " + matcher.group(2));
    }

Using:

String[] subject = line.split("\t",line.length());

will allow me to derive what I need.

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