I am reading input from file it contains set of lines as below :
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
I have to extract the complete line which contains only 172.20.1.5
Below is my code :
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);
}
}
I am expexting output as :
BDI100 172.20.1.5 YES TFTP up up
But is printing all the lines.
This will help you:
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);
}
}
}
}
What you are doing seems a little excessive. Perhaps try this:
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.