【发布时间】:2023-03-23 20:49:01
【问题描述】:
我想将我的正则表达式不仅应用于文本文件的第一行,而且应用于所有行。 目前,它仅在整个适当的匹配位于一行时才匹配。如果适当的匹配在下一行继续 - 它根本不匹配。
class Parser {
public static void main(String[] args) throws IOException {
Pattern patt = Pattern.compile("(include|"
+ "integrate|"
+ "driven based on|"
+ "facilitate through|"
+ "contain|"
+ "using|"
+ "equipped"
+ "integrate|"
+ "implement|"
+ "utilized to facilitate|"
+ "comprise){1}"
+ "[\\s\\w\\,\\(\\)\\;\\:]*\\."); //Regex
BufferedReader r = new BufferedReader(new FileReader("E:/test/test.txt")); // read the file
String line;
PrintWriter pWriter = null;
while ((line = r.readLine()) != null) {
Matcher matcher = patt.matcher(line);
while (matcher.find()) {
try{
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("E:/test/test1.txt", true)));//append any given input
pWriter.println(matcher.group()); //write the result of matcher to the new file
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
System.out.println(matcher.group());
}
}
}
}
【问题讨论】:
-
可以提供测试数据吗?您尝试匹配的表达式之间是否有新行?
-
@Razib:Java 中没有“全局修饰符”,它不需要。但即使在使用它的语言(如 JavaScript 或 Perl)中,它也与这个问题无关。