Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string.split - by multiple character delimiter [duplicate]

Tags:

java

regex

I would like to parse entire file based on all the possible delimiters like commas, colon, semi colons, periods, spaces, hiphens etcs.

Suppose I have a hypothetical string line "Hi,X How-how are:any you?" I should get output array with items Hi,X,How,how,are,any and you.

How do I specify all these delimiter in String.split method?

Thanks in advance.

like image 769
Umesh K Avatar asked Sep 20 '11 22:09

Umesh K


People also ask

Can a string be split on multiple characters?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

How do you split a string by two delimiters?

To split a string with multiple delimiters in Python, use the re. split() method. The re. split() function splits the string by each occurrence of the pattern.


1 Answers

String.split takes a regular expression, in this case, you want non-word characters (regex \W) to be the split, so it's simply:

String input = "Hi,X How-how are:any you?"; String[] parts = input.split("[\\W]"); 

If you wanted to be more explicit, you could use the exact characters in the expression:

String[] parts = input.split("[,\\s\\-:\\?]"); 
like image 73
Mark Elliot Avatar answered Sep 22 '22 04:09

Mark Elliot