Mumfordwiz
Mumfordwiz

Reputation: 1545

Using pattern,matcher in Java

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?

Upvotes: 2

Views: 68

Answers (4)

Bohemian
Bohemian

Reputation: 425043

One simple way is:

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

Upvotes: 0

Mena
Mena

Reputation: 48404

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]

Upvotes: 0

Adam Yost
Adam Yost

Reputation: 3625

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

[^a-z]

Upvotes: 0

Kent
Kent

Reputation: 195079

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]+");

Upvotes: 2

Related Questions