我用正则表达式编写java prorgram,我想从文件中读写
假设输入文件(book.txt)包含句子,例如:我用正则表达式编写java prorgram,我想从文件中读写,java,regex,file-io,Java,Regex,File Io,假设输入文件(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 = "r
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)使用
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();
而不是
System.out.println("Author : " + author);
System.out.println("Title : " + title);
使用
请在发布前尝试快速搜索:为什么这样做:
BufferedWriter bw=new BufferedWriter(new FileWriter(“bookout.txt”,true));bw.write(输入文本);bw.close()代码>当inputtext为空时?这是您必须执行的操作,而不是System.out.println()。
bw.write(inputtext )