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.

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

14 Comments

String[] splitUp = line.split("\\t"); so this?
yes that should it be
nope, still doesn't split
i updated my answer with some test code that works
my output doesn't split
|
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

1 Comment

your regex only works with your example. what happens if the string changes?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.