nightfixed
nightfixed

Reputation: 841

Java Pattern to match String beginning and end?

I have an input that looks like this : 0; expires=2016-12-27T16:52:39 I am trying extract from this only the date, using Pattern and Matcher.

  private String extractDateFromOutput(String result) {
    Pattern p = Pattern.compile("(expires=)(.+?)(?=(::)|$)");
    Matcher m = p.matcher(result);
    while (m.find()) {
      System.out.println("group 1: " + m.group(1));
      System.out.println("group 2: " + m.group(2));
    }
    return result;
  }

Why does this matcher find more than 1 group ? The output is as follows:

group 1: expires=
group 2: 2016-12-27T17:04:39

How can I get only group 2 out of this?

Thank you !

Upvotes: 0

Views: 48

Answers (2)

subodh
subodh

Reputation: 6158

private  String extractDateFromOutput(String result) {
    Pattern p = Pattern.compile("expires=(.+?)(?=::|$)");
    Matcher m = p.matcher(result);
    while (m.find()) {
      System.out.println("group 1: " + m.group(1));
      // no group 2, accessing will gives you an IndexOutOfBoundsException
      //System.out.println("group 2: " + m.group(2));
    }
    return result;
  }

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174726

Because you have used more than one capturing group in your regex.

Pattern p = Pattern.compile("expires=(.+?)(?=::|$)");

Just remove the capturing group around

  1. expires
  2. ::

Upvotes: 3

Related Questions