Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split a string by space, new line, tab, punctuation

Tags:

java

string

everyone.

I have a string like this

String message = "This is the new message or something like that, OK";

And I want to split it into array

String[] dic = {"this", "is", "the", "new", "message", "or", "something", "like", "that", "OK"};

I used

message = message.split("\\s+");

The problem was that it contained "that," not "that" like I want. Please teach my how to solve it. Thanks

like image 417
Gia Duong Duc Minh Avatar asked May 12 '12 11:05

Gia Duong Duc Minh


People also ask

How do I split a string into substrings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string with a new line?

To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' . A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence. You can also split a string on the system-dependent line separator string.

How do you split a string by spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


1 Answers

You can do

String[] dic = message.split("\\W+");

The \\W means not an alphanumeric character.

like image 77
Garrett Hall Avatar answered Oct 19 '22 23:10

Garrett Hall