java - How to split() a String while maintaining whitespace -
this question has answer here:
- how split string, keep delimiters? 22 answers
how split string of words , retain whitespaces?
here code:
string words[] = s.split(" "); string s contains: hello world
after code runs, words[] contains: "hello" "" world
ideally, should not empty string in middle, contain both whitespaces: words[] should be: "hello" " " " " world
how have result?
you use lookahead/lookbehind assertions:
string[] words = "hello world".split("((?<=\\s+)|(?=\\s+))"); where (?<=\\s+) , (?=\\s+) zero-width groups.
Comments
Post a Comment