Last active
April 25, 2018 11:57
-
-
Save liptga/a75b1ae624cf1ccf69b81e915d51dbd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Prints: | |
" " | |
"fdsajfklsdjalkf" | |
" " | |
"safd" | |
" " | |
"safsdfasdf" | |
" " | |
"sdafdsa" | |
" " | |
"dsafsdafff" | |
" " | |
*/ | |
public static void main(String[] args) { | |
String text = " fdsajfklsdjalkf safd safsdfasdf sdafdsa \t dsafsdafff "; | |
Pattern pattern = Pattern.compile( "(\\s+(?=(\\S|$))|\\S+(?=(\\s|$)))" ); | |
StreamSupport.stream(new MatcherSpliterator(pattern.matcher(text)),false) | |
.forEach(token -> System.out.println("\"" + token + "\"")); | |
} | |
private static class MatcherSpliterator extends Spliterators.AbstractSpliterator<String> { | |
private final Matcher matcher; | |
public MatcherSpliterator(Matcher m) { | |
super(Long.MAX_VALUE, 0); | |
matcher=m; | |
} | |
@Override | |
public boolean tryAdvance(Consumer<? super String> action) { | |
if(!matcher.find()) { | |
return false; | |
} | |
action.accept(matcher.group(1)); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment