簡體   English   中英

用正則表達式解析多行

[英]parsing multiple lines with regex

我正在用Java編寫一個解析bibtex庫文件的程序。 每個條目都應解析為字段和值。 這是一個庫中一個單一bibtex的示例。

@INPROCEEDINGS{conf/icsm/Ceccato07,
  author = {Mariano Ceccato},
  title = {Migrating Object Oriented code to Aspect Oriented Programming},
  booktitle = {ICSM},
  year = {2007},
  pages = {497--498},
  publisher = {IEEE},
  bibdate = {2008-11-18},
  bibsource = {DBLP, http://dblp.uni-trier.de/db/conf/icsm/icsm2007.html#Ceccato07},
  crossref = {conf/icsm/2007},
  owner = {Administrator},
  timestamp = {2009.04.30},
  url = {http://dx.doi.org/10.1109/ICSM.2007.4362668}
}

在這種情況下,我只是讀取該行並使用split方法對其進行了拆分。 例如,第一個條目(作者)的解析如下:

Scanner in = new Scanner(new File(library.bib));
in.nextLine();                                        //skip the header
String input = in.nextLine();                         //read (author = {Mariano Ceccato},)
String field = input.split("=")[0].trim();            //field = "author"
String value = input.split("=")[1];                   //value = "{Mariano Ceccato},"
value = value.split("\\}")[0];                        //value = "{Mariano Ceccato"
value = value.split("\\{")[1];                        //value = "Mariano Ceccato"
value = value.trim;                                   //remove any white spaces (if any)

知道每件事都是好的。 但是,庫中有一個bibtex,它具有多行的值:

@ARTICLE{Aksit94AbstractingCF,
  author = {Mehmet Aksit and Ken Wakita and Jan Bosch and Lodewijk Bergmans and
  Akinori Yonezawa },
  title = {{Abstracting Object Interactions Using Composition Filters}},
  journal = {Lecture Notes in Computer Science},
  year = {1994},
  volume = {791},
  pages = {152--??},
  acknowledgement = {Nelson H. F. Beebe, Center for Scientific Computing, University of
  Utah, Department of Mathematics, 110 LCB, 155 S 1400 E RM 233, Salt
  Lake City, UT 84112-0090, USA, Tel: +1 801 581 5254, FAX: +1 801
  581 4148, e-mail: \path|beebe@math.utah.edu|, \path|beebe@acm.org|,
  \path|beebe@computer.org|, \path|beebe@ieee.org| (Internet), URL:
  \path|http://www.math.utah.edu/~beebe/|},
  bibdate = {Mon May 13 11:52:14 MDT 1996},
  coden = {LNCSD9},
  issn = {0302-9743},
  owner = {aljasser},
  timestamp = {2009.01.08}
}

如您所見,確認字段不僅限於一行,因此我無法使用nextLine()讀取。 如果將它作為String傳遞給它,我的解析函數就可以正常使用。 那么,讀取此條目以及其他多行條目和stile能夠讀取單行條目的最佳方法是什么?

對於這些問題之王,最好使用特定的解析器。 我搜索了bibtex解析器並找到了

如果您喜歡自己做的事情,此問題的一種解決方法是檢查該行是否以},結尾},如果沒有,請在當前行之后添加下一行。

話雖如此,可能還有其他問題,這就是為什么我建議使用解析器的原因

這些條目的形式是

@<type>{<Id>
<name>={<value>},
....
<name>={<value>}
}

請注意,姓氏/值對后面沒有逗號。

如果將值分成多行,則僅表示特定行尚不包含右括號。 在這種情況下,請掃描下一行並將其附加到要拆分的字符串上。 繼續執行此操作,直到字符串中的最后一個字符為“}”或“}”(如果“確認”是記錄中的最后一個“名稱/值”對,則將發生后者)。

為了增加安全性,請計算閉合括號的數量與閉合括號的數量相匹配,並繼續在字符串上附加行,直到行為止。 這將涵蓋您在某篇文章中標題過長而不幸在錯誤的位置中斷的情況,例如

title = {{Abstracting Object Interactions Using Composition Filters, and other stuff}
}, 

暫無
暫無

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

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