Skip to content
Advertisement

How to split a string by a newline and a fixed number of tabs like “nt” in Java?

My input string is the following:

 String input = "dirntsubdir1ntsubdir2nttfile.ext";

My intended result is

  • dir,
  • subdir1,
  • subdir2nttfile.ext

The requirement is to split the input by “nt” but not “ntt”. A simple try of

String[] answers = input.split("nt");

also splits “tfile.ext” from the last entry. Is there a simple regular expression to solve the problem? Thanks!

Answer

You can split on a newline and tab, and assert not a tab after it to the right.

nt(?!t)

See a regex demo.

String input = "dirntsubdir1ntsubdir2nttfile.ext";
String[] answers = input.split("\n\t(?!\t)");
System.out.println(Arrays.toString(answers));

Output

[dir, subdir1, subdir2
        file.ext]
Advertisement