假设输入文件(book.txt)包含句子,例如:
book 'learning java' for doctor ahmed mohamed.
the best title is:How to program for simth sahg.
我想从文件(book.txt)中读取每个句子,而不是从键盘输入,并将文件中的每个句子与3种模式匹配:
String p1 = "(book|\\)|\\:) (.*) for( doctor| author|) (.*)";
String p2 = "regex two";
String p3 = "regex three";
// matcher for each of the patterns .
Matcher m1=Pattern.compile(p1).matcher(inputtext);
Matcher m2=Pattern.compile(p2).matcher(inputtext);
Matcher p3=Pattern.compile(p3).matcher(inputtext);
如果句子匹配任何模式,那么将在新文件中提取并写入[作者,标题](bookout.txt)
或不匹配任何模式写“句子”不匹配(bookout.txt)
鳕鱼是 String p1 = "(book|\\)|\\:) (.*) for( doctor| author|) (.*)";
String p2 = "regex two";
String p3 = "regex three";
String inputtext = null;
// matcher for each of the patterns .
Matcher m1=Pattern.compile(p1).matcher(inputtext);
Matcher m2=Pattern.compile(p2).matcher(inputtext);
Matcher m3=Pattern.compile(p3).matcher(inputtext);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("bookout.txt",true));
BufferedReader br = new BufferedReader(new FileReader(new File("book.txt") ));
inputtext= br.readLine();
while ((inputtext=br.readLine())!= null)
System.out.println(inputtext);
String author=null;
String title = null;
if (m1.find()) { //if input matches p1
title = m1.group(2).trim();
author = m1.group(4).trim();
} else if (m2.find()) { //else if input matches p2
title = m2.group(1).trim();
author = m2.group(3).trim();
} else if (m3.find()) { //else if input matches p3
author = m3.group(2).trim();
title = m3.group(4).trim();
}
if (author ==null || title == null) { //If no matches set the author and title strings...
bw.write("inputNot match"); //There's no match
} else { //Otherwise...
bw.write("Author : " + author);
bw.write("Title : " + title);
bw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
请帮帮我,如何在控制台上显示输出而不是显示将写入另一个文件(bookout.txt)
答案 0 :(得分:0)
使用BufferedWriter
将输出写入文件。例如:
BufferedWriter bw = new BufferedWriter(new FileWriter("bookout.txt",true));
// write to the file
bw.write("Author : " + author);
// close the writer when you have finished writing everything
bw.close();
答案 1 :(得分:0)
而不是
System.out.println("Author : " + author);
System.out.println("Title : " + title);
使用
bw.write(inputtext )