Merve K.
Merve K.

Reputation: 37

spliting a string by space and dot and comma at the same time

How can I split a string by space, dot and comma at the same time? I want to get rid of them and get words only.

My code for space:

str=array.get(0).split(" ");

After advices i wrote this

 str=array.get(0).split("[ ]|[.]|[,]|[ \t]");

but i see a new problem

String

New problem

Upvotes: 0

Views: 6103

Answers (2)

Paschoal
Paschoal

Reputation: 175

The method split can be used with a Regex pattern, so you can match more elaborated cases to split your string.

A matching pattern for your case would be:

[ \.,]+

Regex Exaplanation:
[ .,]+ - The brackets create Character Set, that will match any character in the set.
[ .,]+ - The plus sign is a Quantifier, it will match the previous token (the character set) one or more times, this solves the problem where the tokens are following one another, creating empty strings in the array.

You can test it with the following code:

class Main {
  public static void main(String[] args) {
    String str = "Hello, World!, StackOverflow. Test Regex";
    String[] split = str.split("[ .,]+");
    for(String s : split){
      System.out.println(s);
    }    
  }
}

The output is:
Hello
World!
StackOverflow
Test
Regex

Upvotes: 2

Filip Meštrović
Filip Meštrović

Reputation: 139

Using .split() can lead to having empty entries in your array.

Try this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String text = "This is... a real sentence, actually.";

Pattern reg = Pattern.compile("\\w+");
Matcher m = reg.matcher(text);

while (m.find()) {
    System.out.println(m.group());
}

Upvotes: 4

Related Questions