[英]Regex matching with pattern and matches
我正在從文件中讀取輸入,它包含一組行,如下所示:
BDI100 172.20.1.5 YES TFTP up up BDI500 172.20.1.50 YES TFTP up up BDI600 172.20.1.58 YES TFTP up up
我必須提取僅包含172.20.1.5的完整行
以下是我的代碼:
while ((line = lineNumberReader.readLine()) != null) {
Pattern p = Pattern.compile(expr.trim()); /*expr is filter contains 172.20.1.5 */
Matcher m = p.matcher(line);
if(m.find()){
System.out.println(line);
}
}
我將輸出視為:
BDI100 172.20.1.5 YES TFTP up up
但是打印所有的線條。
這將有助於您:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String[] lines = new String[]{"BDI100 172.20.1.5 YES TFTP up up",
"BDI500 172.20.1.50 YES TFTP up up",
"BDI600 172.20.1.58 YES TFTP up up"};
Pattern p = Pattern.compile("172\\.20\\.1\\.5\\s");
for (String line : lines) {
Matcher m = p.matcher(line);
if (m.find()) {
System.out.println(line);
}
}
}
}
你在做什么似乎有點過分。 也許嘗試這個:
String need = "172.20.1.5";
String line = "";
while ((line = lineNumberReader.readLine()) != null) {
if (line.trim().equals("")) {
continue:
}
if (line.contains(need) {
System.out.println(line);
break;
}
}
/*Intialize expr within braces */
String expr = "(172.20.1.5 )";
while ((line = lineNumberReader.readLine()) != null) {
Pattern p = Pattern.compile(expr.trim()); /*expr is filter contains 172.20.1.5 */
Matcher m = p.matcher(line);
if(m.find()){
System.out.println(line);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.