簡體   English   中英

用於在文件中匹配的java Regex

[英]java Regex for matching in file

我想在日志文件(是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似乎是'!!!!

示例:pattern:\\ A(\\ RequirePackage \\ s *([(\\ s | \\ w |,) ])?\\ s {\\ w +} \\ s *([(\\ d |。)+])?| \\ PassOptionsToPackage \\ s * {\\ w +} \\ s * {\\ w +} |%。 $ | \\ input {[^ {}] } | \\ s)* \\(documentstyle | documentclass)

是我的乳膠主文件的模式。 一個這樣的文件部分附加:

\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. 

如何解決這個問題?

如果需要多行匹配且日志文件不是太大,可以用一個字符串讀取整個文件:

String content = new Scanner(file).useDelimiter("\\Z").next();

然后針對content運行正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM