1
"2/17/2014 11:55:00 PM"

I want to split the above string in Java into the following parts: 2, 17, 2014, 11, 55, 00, PM.

I was thinking of using something like-

String[] parts = string.split("[/ :]");

but it doesn't seem to be working. I would like to split everything in one command, if at all possible.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Alex
  • 197
  • 1
  • 1
  • 4

5 Answers5

1

Try:

String[] strings = "2/17/2014 11:55:00 PM".split("/| |:");

Also try replacing with ", " if you want just one String:

 String x = "2/17/2014 11:55:00 PM".replaceAll("/| |:", ", ");
Yser
  • 2,086
  • 22
  • 28
1

I think there's a problem with the way you're looking for spaces. Try

[:\\s\\/]

It will look for a colon (:), a "space character" (tab or space), and then a slash (which you have to escape with a backslash).

John
  • 1,440
  • 1
  • 11
  • 18
0

You can split using a regex expression like so:

public class Test {
    public static void main(String[] args) {
        String s = "2/17/2014 11:55:00 PM";
        String[] parts = s.split("/|:| ");
        for (String p : parts)
            System.out.println(p);  
    }   
}

The pipe '|' operator in the regex expression means OR. So your criteria is forward slash, colon, or space.

This produces the following.

$ javac Test.java
$ java Test
2
17
2014
11
55
00
PM
ktm5124
  • 11,861
  • 21
  • 74
  • 119
0

This is answered here, guess: Use String.split() with multiple delimiters

String a="2/17/2014 11:55:00 PM";
String[]tokens = a.split("/| |:");

Try it

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
0

it works for me :

  String s="2/17/2014 11:55:00 PM";
  String[] parts = s.split("[/ :]");

The output :

for (String s: parts)
    System.out.println(s);

==>

run:
2
17
2014
11
55
00
PM
BUILD SUCCESSFUL (total time: 0 seconds)
Zied R.
  • 4,964
  • 2
  • 36
  • 67