split
will only cuts the whole string at where it founds a #. That explain your current result.
You may want to extract the first word of every pieces of string, but the good tool to perform your task is RegEx
Here how you can achieve it:
String line = "#food was testy. #drink lots of. #night was fab. #three #four";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(line);
while (matcher.find())
{
System.out.println(matcher.group());
}
Output is:
#food
#drink
#night
#three
#four
The magic happen in "#\w+".
So we search for stuff starting with #
followed by one or more letter, number or underscore.
We use '\\' for '\' because of Escape Sequences.
You can play with it here.
find
and group
are explained here:
- The
find
method scans the input sequence looking for the next subsequence that matches the pattern.
group()
returns the input subsequence matched by the previous match.
[edit]
The use of \w
can be an issue if you need to detect accented characters or non-latin characters.
For example in:
"Bonjour mon #bébé #chat."
The matches will be:
It depends on what you will accept as possible hashTag. But it is an other question and multiple discussions exist about it.
For example, if you want any characters from any language, #\p{L}+
looks good, but the underscore is not in it...