2014-07-04 70 views
0

我在當一個行是這樣的txt文件:如何使局部變量外循環訪問在java中

"Execution Status: Pass"

我想利用數值超出:通過從這裏開始。

我使用下面的代碼:

String patternString1 = "(Execution) (Status:) (.*)"; 
Pattern patt1 = Pattern.compile(patternString1); 
BufferedReader r = new BufferedReader(new FileReader("c:\\abc.txt")); 
String line; 
while ((line = r.readLine()) != null) { 
    String g11 = null; 
    Matcher m1 = patt1.matcher(line); 
    while (m1.find()) { 
     g11=m1.group(3); 
     System.out.println(g11+"HI1"); //Line1 
    } 
    System.out.println(g11+"HI1"); //Line2 
} 

雖然1號線所賜爲「合格」我沒有收到從2號線 這個預期產量可能你的任何一個請幫我在期望的輸出從循環中訪問局部變量?

+0

你在哪裏聲明'g11'開始的局部變量? – christopher

+0

在內部while循環之外 – Abuzar

+0

一個簡單的方法將簡單地使用'line.split(「:」);' –

回答

0

申報字符串作爲G11在你的方法

String g11=""; -- declare g11 as a local variable 
    String patternString1 = "(Execution) (Status:) (.*)"; 
    Pattern patt1 = Pattern.compile(patternString1); 

Add the rest of your code here......... 
+0

thansk非常適合您的答案 – Abuzar

0

你能嘗試改變下面一行:

while (m1.find()) 

if(m1.find()) 

它應該給結果你想

+0

我不認爲改變循環從while以解決問題。我試過了,不起作用 – Abuzar

+0

輸出是什麼? –

0

如何最簡單的方法:

String result = line.replaceAll(".*: ", ""); 

這條線說「將所有內容全部替換爲冒號空格」(即刪除它)。

+0

嗨波希米亞人,這不是一個單行的txt文件。它有許多不同特徵的線條。所以我不能使用那個分割。匹配者在這方面更好,因爲我只能說 – Abuzar

0

如果在單行中只有一個此匹配的實例,則使用if而不是while (m1.find())循環或break找到循環一次匹配。

示例代碼:

while ((line = r.readLine()) != null) { 
    String g11 = null; 
    Matcher m1 = patt1.matcher(line); 
    if(m1.find()) { 
     g11=m1.group(3);    
    } 
    if(g11 != null){ 
     System.out.println(g11+"HI1"); //Line2 
    } 
} 
+0

對不起拉吉,它不是一個好主意。如果我們有另一個匹配器說m2,那麼這個條件是無效的 – Abuzar

+0

@ user3777979我不知道你在做什麼? – Braj

相關問題