Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string into words and punctuation with java

Tags:

java

string

regex

I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.

For instance: String c = "help, me!"

I want out the list to look like is:

['help', ',', 'me', '!']

So, I want the string split at whitespace with the punctuation split from the words. Do you have ideas how to do it?

like image 785
Rudziankoŭ Avatar asked Dec 11 '22 06:12

Rudziankoŭ


2 Answers

Try this

String str = "help, me!";
        StringTokenizer st = new StringTokenizer(str, ", !", true);
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());;
        }

Output:

help
,
   <- space
me
!
like image 182
tana Avatar answered Jan 01 '23 10:01

tana


You can do it using regex as follows:

String d = Str.split("\\W+");

Updated answer for your question:

String d = Str.split("\\b");
like image 25
sshashank124 Avatar answered Jan 01 '23 11:01

sshashank124