简体   繁体   English

Java在空格处分割字符串,但保留制表符

[英]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. 我有一个课程的字符串"4612 CMP Computer Science Java II CMP110 A- 010" I need to get the "Computer Science" and "Java II" bits. 我需要获取“计算机科学”和“ Java II”位。 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. 4612之后是“制表符”,也位于“科学”和“ 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. 可以让我得出我需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM