如何将文件行与带占位符的字符串进行比较?
How can I compare file line to strings with placeholders?
我希望将文件中的一行与带占位符的字符串进行比较。
该文件包含来自计算机(Windows 和 Linux 机器)的已用 COM
、ACM
、USB
端口的列表,我想要将 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
子字符串添加到地址列表。
我被引导相信我可以使用格式化的占位符来做到这一点,但我如何将它集成到这个 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)
等等
我希望将文件中的一行与带占位符的字符串进行比较。
该文件包含来自计算机(Windows 和 Linux 机器)的已用 COM
、ACM
、USB
端口的列表,我想要将 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
子字符串添加到地址列表。
我被引导相信我可以使用格式化的占位符来做到这一点,但我如何将它集成到这个 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)
等等