从java中提取特定行

从java中提取特定行,java,string,parsing,design-patterns,Java,String,Parsing,Design Patterns,我有一个如下所示的文本文件 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 devi

我有一个如下所示的文本文件

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

现在这个数字可能会有所不同。我怎样才能有效地提取这个。前置码行号不是恒定的

只保留以数字开头的行

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

如果您需要的行总是以一个数字开头,那么您可以使用下面的方法检查是否是这样

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

逐行读取文本文件。对于每一行,如果字符串以“添加设备”或以“\t名称:”开头,则忽略这些行。例如:

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

尝试使用正则表达式:

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

你的方法行得通,我实际上在寻找一种模式,你已经找到了。