I have this code:
String s = "bla mo& lol!";
Pattern p = Pattern.compile("[a-z]");
String[] allWords = p.split(s);
I'm trying to get all the words according to this specific pattern into an array. But I get all the opposite.
I want my array to be:
allWords = {bla, mo, lol}
but I get:
allWords = { ,& ,!}
Is there any fast solution or do I have to use the matcher and a while loop to insert it into an array?
4 Answers 4
Pattern p = Pattern.compile("[a-z]");
p.split(s);
means all [a-z] would be separator, not array elements. You may want to have:
Pattern p = Pattern.compile("[^a-z]+");
Comments
You are splitting s AT the letters. split uses for delimiters, so change your pattern
[^a-z]
Comments
The split method is given a delimiter, which is your Pattern.
It's the inverted syntax, yet the very same mechanism of String.split, wherein you give a Pattern representation as argument, which will act as delimiter as well.
Your delimiter being a character class, that is the intended result.
If you only want to keep words, try this:
String s = "bla mo& lol!";
// | will split on
// | 1 + non-word
// | characters
Pattern p = Pattern.compile("\\W+");
String[] allWords = p.split(s);
System.out.println(Arrays.toString(allWords));
Output
[bla, mo, lol]
Comments
One simple way is:
String[] words = s.split("\\W+");