2016-12-27 101 views
0

我有一個input,看起來像這樣:0; expires=2016-12-27T16:52:39 我從這個只有日期試圖提取物,使用PatternMatcher匹配字符串開始和結束的Java模式?

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; 
    } 

爲什麼這是否匹配找到比1組嗎?輸出如下:

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

我怎樣才能得到只有2組出的呢?

謝謝!

+0

你是什麼意思?你自己在模式中定義了3個捕獲組。那麼只需使用'm.group(2)'。 –

回答

3

因爲您在正則表達式中使用了多個捕獲組。

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

只需卸下捕獲組圍繞

  1. expires
  2. ::
0
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; 
    } 
相關問題