Reputation: 53
I have String s = "#stack###over##flow".
How do I split s
to have
String[] a = {"#", "stack", "###", "over", "##", "flow}
I tried s.split("(?<=#)|(?=#)")
as in How to split a string, but also keep the delimiters? but it gives
String[] a = {"#", "stack", "#", "#", "#", "over", "#", "#", "flow}
Upvotes: 4
Views: 72
Reputation: 70732
The lookarounds need to be a little more assertive, meaning that the look-behind needs to assert that the following position is either a word character or not a #
and the lookahead needs to assert that the preceding position is either a word character or not a #
as well.
You could use word boundaries in each alternation:
String s = "#stack###over##flow";
String[] a = s.split("(?<=#\\b)|(?=\\b#)");
System.out.println(Arrays.toString(a)); //=> [#, stack, ###, over, ##, flow]
Or modify your lookaround assertions ( longer approach ):
String[] a = s.split("(?<=#(?!#))|(?<=[^#](?=#))");
Upvotes: 5