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.
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.
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.
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\\-:\\?]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With