Java正则表达式用于文件匹配

3

我希望能够在一个日志文件(是的,是tex-log文件)中找到由正则表达式模式定义的警告,并且还要在tex文件中找到表示它是主文件的模式。

为此,我逐行读取文件并匹配模式。只要模式只有一行,这个方法就可以很好地工作。

// may throw FileNotFoundException < IOExcption 
FileReader fileReader = new FileReader(file);
// BufferedReader for perfromance 
BufferedReader bufferedReader = new BufferedReader(fileReader);
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);//

// readLine may throw IOException 
for (String line = bufferedReader.readLine();
  line != null;
  // readLine may thr. IOException
  line = bufferedReader.readLine()) {
  if (pattern.matcher(line).find()) {
    return true;
  }
}
return false;

如果文本跨越多行,这种方法就变得困难了。
我尝试过。
CharBuffer chars = CharBuffer.allocate(1000);
// may throw IOException 
int numRead = bufferedReader.read(chars);
System.out.println("file: "+file);
System.out.println("numRead: "+numRead);
System.out.println("chars: '"+chars+"'");
return pattern.matcher(chars).find();

但是这并没有起到作用:完全没有匹配!!numRead产生了1000,而chars似乎是''!

例子:模式: \A(\RequirePackage\s*([(\s|\w|,)])?\s{\w+}\s*([(\d|.)+])?| \PassOptionsToPackage\s*{\w+}\s*{\w+}| %.$| \input{[^{}]}| \s)* \(documentstyle|documentclass)

这是我的latex主文件的模式。 其中一个这样的文件部分附在此处:

\RequirePackage[l2tabu, orthodox]{nag}
\documentclass[10pt, a4paper]{article}

\usepackage[T1]{fontenc}
\usepackage{fancyvrb}

\title{The dvi-format and the program dvitype}
\author{Ernst Reissner (rei3ner@arcor.de)}

\begin{document}

\maketitle
\tableofcontents

\section{Introduction}
This document describes the dvi file format 
traditionally used by \LaTeX{} 
and still in use with \texttt{htlatex} and that like. 

如何解决这个问题?

3
请更新您的问题,展示给我们 a) 您正在尝试匹配的正则表达式模式和 b) 应该匹配的日志文件样本。 - Tim Biegeleisen
1个回答

0
如果您需要多行匹配且日志文件不太大,您可以将整个文件读入一个字符串中:
String content = new Scanner(file).useDelimiter("\\Z").next();

然后对content运行正则表达式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接