2012-09-05 43 views
0

我有一個文本文件就像下面提取特定的線路在java

add device 1: /dev/input/event7 
    name:  "evfwd" 
add device 2: /dev/input/event6 
    name:  "aev_abs" 
add device 3: /dev/input/event5 
    name:  "light-prox" 
add device 4: /dev/input/event4 
    name:  "qtouch-touchscreen" 
add device 5: /dev/input/event2 
    name:  "cpcap-key" 
add device 6: /dev/input/event1 
    name:  "accelerometer" 
add device 7: /dev/input/event0 
    name:  "compass" 
add device 8: /dev/input/event3 
    name:  "omap-keypad" 
4026-275085: /dev/input/event5: 0011 0008 0000001f 
4026-275146: /dev/input/event5: 0000 0000 00000000 
4026-494201: /dev/input/event5: 0011 0008 00000020 
4026-494354: /dev/input/event5: 0000 0000 00000000 

什麼,我需要做的是我要刪除的添加設備的前導,我只需要從4026-275開始的所有行... 即

4026-275085: /dev/input/event5: 0011 0008 0000001f 
    4026-275146: /dev/input/event5: 0000 0000 00000000 
    4026-494201: /dev/input/event5: 0011 0008 00000020 
    4026-494354: /dev/input/event5: 0000 0000 00000000 

現在這個數字可以變化。我怎樣纔能有效地提取這個。前導碼行號不是固定的。

回答

1

只保留以數字開頭的行。

for (String line : lines) { 
    if (line.matches("^\\d+.*")) { 
     System.out.println("line starts with a digit"); 
    } 
} 
+0

你的方法工作,我一直在尋找一個模式實際上和u有它。 –

0

如果總是出現需要的行以數字開頭的情況,可以使用類似下面的內容來檢查是否是這種情況。

String[] lines = figureOutAWayToExtractLines(); 

// Iterate all lines 
for(String line : lines) 
    // Check if first character is a number (optionally trim whitespace) 
    if(Character.isDigit(str.charAt(0))) 
     // So something with it 
     doSomethingWithLine(line); 
0

逐行讀取文本文件。對於每一行,如果字符串起始於「添加設備」或startsWith「\ tname:」,那麼只需忽略這些行。例如:

final String line = reader.readLine(); 
if(line != null) { 
    if(line.startsWith("add device") || line.startsWith("\tname:")) { 
     // ignore 
    } 
    else { 
     // process 
    } 
} 
0

嘗試用正則表達式:

boolean keepLine = Pattern.matches("^\d{4}-\d{6}.*", yourLine);