2

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

2
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]+");
Sign up to request clarification or add additional context in comments.

Comments

0

You are splitting s AT the letters. split uses for delimiters, so change your pattern

[^a-z]

Comments

0

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

0

One simple way is:

String[] words = s.split("\\W+");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.