0
String[] splitUp = line.split("\t");

This is the code and the string is this "John Doe 3.30 23123123" The problem is at the end of Doe and after 3.30 those spaces are actually tabs. Now I have to split up this string by the tabs and \t and \t aren't working. Help

Here is more code:

while(scan.hasNextLine()){


          String line = scan.nextLine();
          String[] splitUp = line.split("\\t");
          for(int i = 0; i < splitUp.length; i++){
              System.out.println(splitUp[i]);
          }

}

and I have a text file which is feeding in lines with tabs.

Answer:

if editing a .txt file with the java compiler IntelliJ then it replaces the \t char with the corresponding amount of spaces, therefore you cannot check for \t because it doesn't exist. you have to edit it in a regular text editor and all will be good.

Sam Hoffmann
  • 310
  • 2
  • 15

2 Answers2

0

in java you need \\t to also escape the \.

following code works:

String test="asd    asd asd xsdv";
String[]t=test.split("\\t");
for(String st : t){
    System.out.println(st);
}

output is:

asd
asd
asd xsdv
XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
0

You can use it and then save each group => Array

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(\\w+\\s\\w+|\\d+.\\d+)";
final String string = "John Doe 3.30    23123123";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

Input:

John Doe    3.30    23123123

Output:

John Doe
3.30
23123123

See: https://regex101.com/r/Us6G3X/1