如何将文件行与包含占位符的字符串进行比较?

问题描述 投票:0回答:1

我想比较一个文件中的一行到一个带占位符的String。

该文件包含计算机中使用的COMACMUSB端口列表(Windows和Linux机器),我想将COMxACMxUSBx添加到LinkedList,其中x是计算机分配的端口号。

我在做:

// LinkedList<string> addr instantiated before.

// This if structure is inside a while loop reading each line of the file
// and storing it to line that breaks when line = null. Line is set to
// lower case for processing purposes.

if(line.contains("com") || line.contains("acm") || line.contains("usb"))
{
    addr.add(line);
}

它会添加COM6COMBluetooth Device。我正在寻找的方法是获取COM6而不是COMBluetooth Device端口,或者实际上任何其他未编号的端口,然后将此COMx子字符串添加到addr列表。

我一直认为我可以使用格式化的占位符来做到这一点,但是我如何将它整合到这个if语句中呢?如果不是占位符,我该怎么做呢?

java file-io string-comparison
1个回答
0
投票

您可以尝试使用此方法:

private static boolean getResult(String line) {
    Pattern p = Pattern.compile("(COM|ACM|USB)\\d");
    Matcher m = p.matcher(line);
    return m.find();
}

如果您需要添加更多端口,可以添加(COM|ACM|USB|nextPort|next|next)

© www.soinside.com 2019 - 2024. All rights reserved.