Link to home
Start Free TrialLog in
Avatar of VAnvesh
VAnvesh

asked on

JAVA Regex Pattern for XML Gregorian Calender

I have to read file that has text as "#EXT-X-PROGRAM-DATE-TIME:2014-04-17T07:18:02.350+00:00" for every 10 seconds and ill be having such files about 400.

I need to fetch value 2014-04-17T07:18:02.350+00:00

I did a sample program that picks the above value with  substring.

 String aacKey = strLine.substring(strLine.indexOf(#EXT-X-PROGRAM-DATE-TIME:) + 5, strLine.length() - 1);

However, this looks like a costly approach where i see char[] is taking too much of heap space where allocated space isn't enough for the operations.

What is the best approach to address this. Also, what is the regular expression that i can use to fetch using Pattern, Matcher instead of substring().

Appreciate your response.
Thanks :)
Avatar of kaufmed
kaufmed
Flag of United States of America image

what is the regular expression that i can use
String pattern = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d+\\d{2}:\\d{2}";

Open in new window

Avatar of VAnvesh
VAnvesh

ASKER

Hi Kaufmed,

I understand the expression and i believe it is correct. However, when i used for the below program
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringRegex {

    public static void main(String [] a){
        String value = "#EXT-X-PROGRAM-DATE-TIME:2014-04-17T07:18:02.350+00:00";
        Pattern p = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d+\\d{2}:\\d{2}");
        Matcher m = p.matcher(value);
        if(m.find())
        System.out.println(m.group(1));
    }
}

Open in new window


I am unable to get the desired result. Can you let me know where i go wrong.
Try group 0 instead--I didn't include any capture groups in the pattern. Or, you can surround the pattern with parens (see below) and you can stick with group 1.

Pattern p = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d+\\d{2}:\\d{2})");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of VAnvesh

ASKER

solution works flawless. Thanks to Kaufmed.