Alex Rivera | Logout

Use String.split() with multiple delimiters

Asked 2011-05-13T14:56:36.180
253

I need to split a string base on delimiter - and .. Below are my desired output.

AA.BB-CC-DD.zip ->

AA
BB
CC
DD
zip 

but my following code does not work.

private void getId(String pdfName){
    String[]tokens = pdfName.split("-\\.");
}
Edit
Report

3 Answers

363

I think you need to include the regex OR operator:

String[]tokens = pdfName.split("-|\\.");

What you have will match:
[DASH followed by DOT together] -.
not
[DASH or DOT any of them] - or .

answered 2011-05-13T14:59:50.127
72

Try this regex "[-.]+". The + after treats consecutive delimiter chars as one. Remove plus if you do not want this.

answered 2011-05-13T15:00:46.057
32

You can use the regex "\W".This matches any non-word character.The required line would be:

String[] tokens=pdfName.split("\\W");
answered 2012-12-18T07:14:26.277

Your Answer