Andrew
Andrew

Reputation: 8703

Delimiter in scanner, keep delimiters

I have a file like so:

foo|blah
bar
baz
foo|moreblah
morebar
morebaz

I want to split it at foo. So I've got

scanner.useDelimiter("foo")

This almost works, except that in the output I'm losing the delimiter "foo". In other words, for the first chunk, I end up with

|blah
bar
baz

How do I keep the delimiter?

Upvotes: 0

Views: 64

Answers (2)

Bohemian
Bohemian

Reputation: 425003

Split using a look ahead, which asserts that the following input is "foo" without consuming it, and consumes (unwanted) preceding line endings:

String[] parts = str.split("\\R*(?=foo)");

\R means “any line ending”.

FYI split won’t create a leading blank element if the first match is zero width (as here),

Upvotes: 1

WJS
WJS

Reputation: 40034

Does this do it for you? It uses zero width assertions to split around the delimeter. So it preserves it for you.

String text = "foo|blah\nbar\nbaz\nfoo|moreblah\nmorebar\nmorebaz\n";
String regex = "(?<=foo)(?!foo)|(?=foo)(?!<foo)";

String[] vals = text.split(regex);
for (String v : vals) {
    System.out.println(v);
}

Prints

foo
|blah
bar
baz

foo
|moreblah
morebar
morebaz

Upvotes: 3

Related Questions