Extract words from a template

I have String s = "#stack###over##flow". How to divide s by

 String[] a = {"#", "stack", "###", "over", "##", "flow} 

I tried s.split("(?<=#)|(?=#)") , As in How to split a line, but also keep the delimiters? but he gives

 String[] a = {"#", "stack", "#", "#", "#", "over", "#", "#", "flow} 
+4
source share
2 answers

The patterns should be a little more assertive, which means that the look should state that the next position is either a word character or # does not matter, and in lookahead you must say that the previous position is either a # character.

You can use word boundaries in each rotation:

 String s = "#stack###over##flow"; String[] a = s.split("(?<=#\\b)|(?=\\b#)"); System.out.println(Arrays.toString(a)); //=> [#, stack, ###, over, ##, flow] 

Or modify your search statements (longer approach):

 String[] a = s.split("(?<=#(?!#))|(?<=[^#](?=#))"); 
+5
source

I think there is a much more enjoyable way.

looks crazy:

 \b 

Regex live here.

+2
source

All Articles