Zion
Zion

Reputation: 753

Substring of a Date

Hello i have a String like this:6-006.a9&&20130323^000~1-206&&20130329^000~1-208.2&&20130322^000 and i want to get the Date out. I have a working Solution but i think it is to long:

String replace = pw.replace('&', '^');
        String[] rrex = replace.split("\\^+");
        for(String s:rrex)
        {
         if(s.matches("[0-9]{8}"))
         {
             System.out.println(s);
         }
        }

This code is not realy what I want can I get the Date with a regex? Like String[] dates = pw.split(regex);

Upvotes: 3

Views: 270

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174796

Through string.split function.

String s = "6-006.a9&&20130323^000~1-206&&20130329^000~1-208.2&&20130322^000";
String parts[] = s.split("(?:^|\\^)[^&]*(?:&&|$)");
for(String i: parts)
{
    if (!i.isEmpty())
    {
    String out[] = i.split("(?=.{4}$)|(?=.{2}$)");  
    System.out.println("Year : " + out[0] + " month : " + out[1] + " day: " + out[2]);
}
}

Output:

Year : 2013 month : 03 day: 23
Year : 2013 month : 03 day: 29
Year : 2013 month : 03 day: 22

Upvotes: 0

Mena
Mena

Reputation: 48434

You can use the following idiom, iterating over matches:

String test = "6-006.a9&&20130323^000~1-206&&20130329^000~1-208.2&&20130322^000";
//                           ┌ look behind for "&&"
//                           |      ┌ group 1: year
//                           |      |       ┌ group 2: month
//                           |      |       |       ┌ group 3: day
//                           |      |       |       |       ┌ look ahead 
//                           |      |       |       |       | for escaped "^"
Pattern p = Pattern.compile("(?<=&&)(\\d{4})(\\d{2})(\\d{2})(?=\\^)");
// initialize matcher
Matcher m = p.matcher(test);
// iterate matches
while (m.find()) {
    // print matches formatted for each group
    System.out.printf(
        "Found: year %s / month %s / day %s%n", 
        m.group(1), 
        m.group(2), 
        m.group(3)
    );
}

Output

Found: year 2013 / month 03 / day 23
Found: year 2013 / month 03 / day 29
Found: year 2013 / month 03 / day 22

Note

  • There is no validation of the value of month (e.g. > 12 or 00) or day (e.g. > 31, 00, or invalid day index for a given month).
  • I suggest you validate that outside the Pattern once the values are retrieved, in order to avoid cluttering it.
  • This will work for 8-digit date representations only. Tweaking the Pattern to accept optional 1-digit day/month or 2-digit year might clutter it.

Upvotes: 8

Related Questions