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.

5
  • What did you try? What result did you get? "It doesn't work" isn't sufficient for us to help you. Commented Feb 28, 2014 at 21:19
  • Looks like you try to parse a date. Any reason you do not want to use SimpleDateFormat or some JodaTime class to parse it? Commented Feb 28, 2014 at 21:20
  • It works for me. Where's the problem? Commented Feb 28, 2014 at 21:20
  • It is working with me though. Commented Feb 28, 2014 at 21:21
  • Your RegExp works fine, so your problem is probably in the surrounding code. Commented Feb 28, 2014 at 21:22

5 Answers 5

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).

Sign up to request clarification or add additional context in comments.

Comments

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("/| |:", ", ");

Comments

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

Comments

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.