How to split a string by triple dots or horizontal ellipsis

Viewed 1725

I am facing problems when trying to split a String by "..."

    String text ="Here…It is safer.";

I tried:

String [] output = text.split("[\\...]");
String [] output = text.split("\\.");

and many others, but I haven't found the solution yet.

I know that the question is very simple, but I will be happy If somebody can explain how should I make it work.

3 Answers

In general, you can use

String[] chunks = text.split("…|\\.{3}");

To also remove the enclosing whitespace:

String[] chunks = text.split("\\s*(?:…|\\.{3})\\s*");

See this regex demo.

If you need to make sure the triple dots are NOT enclosed with other dot chars, you can add lookarounds:

String[] chunks = text.split("\\s*(?:…|(?<!\\.)\\.{3}(?!\\.))\\s*");

Details:

  • \s* - zero or more whitespaces
  • (?:...) - a non-capturing group
  • … - an ellipsis
  • | - or
  • (?<!\.) - a negative lookbehind that fails the match if there is a dot char immediately to the left of the current location
  • \.{3} - triple dots
  • (?!\.) - a negative lookahead that fails the match if there is a dot char immediately to the right of the current location.

See a Java demo:

String text = "Here…It is safer... The end.";
String[] chunks = text.split("\\s*(?:…|\\.{3})\\s*");
System.out.println(Arrays.toString(chunks));
// => [Here, It is safer, The end.]
Related