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?

arshajii
130k26 gold badges246 silver badges293 bronze badges
asked Jun 12, 2014 at 12:37

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]+");
answered Jun 12, 2014 at 12:40
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]
answered Jun 12, 2014 at 12:40

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]
answered Jun 12, 2014 at 12:42

Comments

0

One simple way is:

String[] words = s.split("\\W+");
answered Jun 12, 2014 at 12:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.