2017-04-20 125 views
1

我想從匹配使用匹配器的模式的字符串中獲取所有輸出,但是,我不確定字符串或模式是否不正確。我試圖得到(服務器:開關)作爲第一個模式等等等等等等,但是,我只是得到最後三種模式,因爲我的輸出顯示。我的輸出與以下RegExpr輸出不正確

found_m: Message: Mess                               
found_m: Token: null                                
found_m: Response: OK 

下面的代碼下面是我的代碼:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class RegexMatches { 

    public static void main(String args[]) { 
     // String to be scanned to find the pattern. 
     String line = "Server: Switch\nMessage: Mess\nToken: null\nResponse: OK"; 
     String pattern = "([\\w]+): ([^\\n]+)"; 

     // Create a Pattern object 
     Pattern r = Pattern.compile(pattern); 

     // Now create matcher object. 
     Matcher m = r.matcher(line); 
     if (m.find()) { 
     while(m.find()) { 
      System.out.println("found_m: " + m.group()); 
     } 
     }else { 
     System.out.println("NO MATCH"); 
     } 
    } 
} 

是我的串線不正確或我的字符串模式的我沒有做regexpr錯了嗎?

在此先感謝。

回答

2

你的正則表達式是差不多正確。

問題是,你打電話find兩次:第一次在if條件,然後再在while

您可以使用do-while循環,而不是:

if (m.find()) { 
    do { 
     System.out.println("found_m: " + m.group()); 
    } while(m.find()); 
} else { 
    System.out.println("NO MATCH"); 
} 

對於正則表達式的一部分,你可以用較小的修正使用:

final String pattern = "(\\w+): ([^\\n]+)"; 

,或者如果你不需要2個捕獲組,然後使用:

final String pattern = "\\w+: [^\\n]+"; 

因爲沒有必要使用左右的字符類

0

我對Java並不熟悉,但是這個正則表達式模式應該能夠捕獲每個組和匹配。

([\w]+): (\w+)(?:(?:[\\][n])|$) 

它基本上指出捕獲字,接着結腸和空間,然後之前任一\ n或字符串的末尾捕捉下一個單詞。

祝你好運。