我想比较一个文件中的一行到一个带占位符的String。
该文件包含计算机中使用的COM
,ACM
,USB
端口列表(Windows和Linux机器),我想将COMx
,ACMx
,USBx
添加到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);
}
它会添加COM6
和COMBluetooth Device
。我正在寻找的方法是获取COM6
而不是COMBluetooth Device
端口,或者实际上任何其他未编号的端口,然后将此COMx
子字符串添加到addr列表。
我一直认为我可以使用格式化的占位符来做到这一点,但是我如何将它整合到这个if
语句中呢?如果不是占位符,我该怎么做呢?
您可以尝试使用此方法:
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)
等