user613114
user613114

Reputation: 2821

JAVA regex failing

I have string which is of format:

;1=2011-10-23T16:16:53+0530;2=2011-10-23T16:16:53+0530;3=2011-10-23T16:16:53+0530;4=2011-10-23T16:16:53+0530;

I have written following code to find string 2011-10-23T16:16:53+0530 from (;1=2011-10-23T16:16:53+0530;)

Pattern pattern = Pattern.compile("(;1+)=(\\w+);");

String strFound= "";
Matcher matcher = pattern.matcher(strindData);
while (matcher.find()) {
   strFound= matcher.group(2);
}

But it is not working as expected. Can you please give me any hint?

Upvotes: 0

Views: 134

Answers (3)

Greg Mattes
Greg Mattes

Reputation: 33949

Do you have to use a regex? Why not call String.split() to break up the string on semi-colon boundaries. Then call it again to break up the chunks by the equals sign. At that point you'll have an integer and the date in string form. From there you can parse the date string.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateScan {
    private static final String INPUT = ";1=2011-10-23T16:16:53+0530;2=2011-10-23T16:16:53+0530;3=2011-10-23T16:16:53+0530;4=2011-10-23T16:16:53+0530;";
    public static void main(final String... args) {
        final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        final String[] pairs = INPUT.split(";");
        for (final String pair : pairs) {
            if ("".equals(pair)) {
                continue;
            }
            final String[] integerAndDate = pair.split("=");
            final Integer integer = Integer.parseInt(integerAndDate[0]);
            final String dateString = integerAndDate[1];
            try {
                final Date date = parser.parse(dateString);
                System.out.println(integer + " -> " + date);
            } catch (final ParseException pe) {
                System.err.println("bad date: " + dateString + ": " + pe);
            }
        }
    }
}

Upvotes: 3

Eugene
Eugene

Reputation: 120858

I've change the input a bit, but just for presentation reasons that is

You can try this:

 String input = " ;1=2011-10-23T16:16:53+0530;   2=2011-10-23T16:17:53+0530;3=2011-10-23T16:18:53+0530;4=2011-10-23T16:19:53+0530;";

Pattern p = Pattern.compile("(;\\d+?)?=(.+?);");
Matcher m = p.matcher(input);

while(m.find()){
    System.out.println(m.group(2));
}

Upvotes: 1

Tomalak
Tomalak

Reputation: 338208

Can you please give me any hint?

Yes. Neither -, nor :, nor + are part of \w.

Upvotes: 4

Related Questions