Gábor DANI
Gábor DANI

Reputation: 2135

How do I split a string in Java to different size parts?

I have a timestamp: 200212312359 How can I split this to 2012.12.31.23.59

The easy way to do is .split("(?<=\\G.{2})"), then combine the first 2 element of the array, but I was wondering if there is any, more professional solution for this.

Upvotes: 1

Views: 839

Answers (4)

Pshemo
Pshemo

Reputation: 124225

As Colleen pointed in comment you can use groups to create new formated date. Here is example

Pattern p = Pattern.compile("^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})$");
Matcher m = p.matcher("200212312359");
StringBuilder sb = new StringBuilder();
if (m.find()) {
    sb.append(m.group(1));
    for (int i = 2; i <= m.groupCount(); i++)
        sb.append(".").append(m.group(i));
}
System.out.println(sb);

output: 2002.12.31.23.59

You can also use named-groups to name every group and use them instead of their numbers:

Pattern p2 = Pattern.compile("^(?<year>\\d{4})(?<month>\\d{2})" +
        "(?<day>\\d{2})(?<hour>\\d{2})(?<minute>\\d{2})$");
Matcher m2 = p2.matcher("200212312359");
if (m2.find()) {
    String formatedDate = m2.group("year") + "." + m2.group("month")
            + "." + m2.group("day") + "." + m2.group("hour") 
            + "." + m2.group("minute");
    System.out.println(formatedDate);
}

You can also update your split to prevent split on first two digits like this

"200212312359".split("(?<=^\\d{4}|(?!^)\\G.{2})"

Upvotes: 0

Also, If you know the position of each value (dot separated), you could use substring method:

 String unformatted = String.valueOf(200212312359);
 String year = unformatted.substring(0,4); 
 String month = unformatted.substring(4,6);
 String day = unformatted.substring(6,8); 
 String hour = unformatted.substring(8,10);
 String minute = unformatted.substring(10,12);
 String formatted = String.format("%s.%s.%s.%s.%s", year, month, day, hour, minute);

Please read http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Upvotes: 0

ɲeuroburɳ
ɲeuroburɳ

Reputation: 7120

You can get the same result with a single replaceAll call and a somewhat overly complex regex.

"200212312359".replaceAll("(^\\d{4}|\\d{2})(?!$)", "$1.")

Broken down, it matches 4-digits at the start ^\\d{4}, or 2-digits \\d{2} anywhere else, with a negative lookahead on the end of input (?!$) to avoid matching the last pair. It then replaces the 4 or 2 digits with the a dot concatenated to the digits.

Upvotes: 6

RouteMapper
RouteMapper

Reputation: 2560

There is nothing necessarily unprofessional about your solution; it just isn't intuitive. If you comment it with a simple explanation of what date format it splits, then that's as professional a solution as any other, IMHO.

Upvotes: 0

Related Questions