Nisha Shlaymoon Nisha Shlaymoon - 3 months ago 8
Java Question

Java regex split String into an array of numbers

I have a scanner String input in the following format: 12:00:00PM.

I managed to finally isolate PM or AM by this:

public class ConverTime
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String timeString = sc.next();

String[] pmOrAm = timeString.split("\\d");
String[] nums = timeString.split("(: + \\D)");

// PM or AM
String timeType = pmOrAm[pmOrAm.length - 1];
for (String n: nums)
{
System.out.println(n);
}
}
}


I know the way I isolate PM or AM is not the best, so hopefully there is a better way where i can get an array of exactly one string.

But when I run the for loop for the "nums" array, the output is:

12:00:00PM


I want the output to be like so:

12
00
00


without the "PM" or "AM." How do I go about this?

Answer

an easy way could be:

timeString.split("(AM|PM|:)")

Hope it helps