2014-11-29 1 views
0

Этот класс открывает файл с разделителями // и возвращает строку. Затем я использую наборы шаблонов с Matcher для поиска строки и возврата фрагментов данных. Позже это будет использоваться для переформатирования данных во множество файлов и конкретных заказов. На данный момент этот процесс работал с несколькими совпадениями шаблонов, но когда я передаю EditorList и AuthorList, он возвращает null, когда данные явно там. Позднее программа выйдет из строя, когда пытается использовать пустые строки, и я получаю исключение нулевого указателя. Это мой первый раз, когда я использовал Pattern и Matcher, что я, очевидно, не хочу делать здесь?Java Matcher Matcher возвращает null после работы с девятью предыдущими аналогичными шаблонами/совпадениями

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class MatchMethod { 
public static String cancerCat=null;  
public static String paperType="book"; 
public static String Paper=null; 
public static String Title=null; 
public static String Abstr=null; 
public static String Publi=null; 
public static String Editi=null; 
public static String Pagen=null; 
public static String Bookt=null; 
public static String Years=null; 
public static String Editl=null; 
public static String Edito=null; 
public static String Authl=null; 
public static String Autho=null; 
public static String Foren=null; 
public static String Initi=null; 
public static String Lastn=null; 

public static Scanner scanner; 
public static File file; 

static Pattern PaperBegin = Pattern.compile("<PaperBegin>(.+?)</PaperBegin>"); 
static Pattern PaperTitle = Pattern.compile("<PaperTitle>(.+?)</PaperTitle>"); 
static Pattern Abstract = Pattern.compile("<Abstract>(.+?)</Abstract>"); 
static Pattern BookTitle = Pattern.compile("<BookTitle>(.+?)</BookTitle>"); 
static Pattern Publisher = Pattern.compile("<Publisher>(.+?)</Publisher>"); 
static Pattern Edition = Pattern.compile("<Edition>(.+?)</Edition>"); 
static Pattern Page =  Pattern.compile("<Page>(.+?)</Page>"); 
static Pattern EditorList = Pattern.compile("<EditorList>(.+?)</EditorList>"); 
static Pattern Editor =  Pattern.compile("<Editor>(.+?)</Editor>"); 
static Pattern Year =  Pattern.compile("<Year>(.+?)</Year>"); 
static Pattern AuthorList = Pattern.compile("<AuthorList>(.+?)</AuthorList>"); 
static Pattern Author =  Pattern.compile("<Author>(.+?)</Author>"); 
static Pattern ForeName = Pattern.compile("<ForeName>(.+?)</ForeName>"); 
static Pattern Initials = Pattern.compile("<Initials>(.+?)</Initials>"); 
static Pattern LastName = Pattern.compile("<LastName>(.+?)</LastName>"); 

public static String find (String text, Pattern pattern) 
{ 
    String found=null; 
    Matcher match = pattern.matcher(text); 
    if (match.find()) {found = match.group(1);} 
    System.out.println((pattern.toString()) + " found: "+found); 
    return found; 
} 

@SuppressWarnings("resource") 
static void readBook (String book) throws FileNotFoundException 
{ 
    file = new File (book); 
    scanner = new Scanner(file).useDelimiter("\\//"); 
    while (scanner.hasNext()) 
    {   
     Paper=scanner.next(); 
     Title = find (Paper, PaperTitle); 
     Abstr = find (Paper, Abstract); 
     Publi = find (Paper, Publisher); 
     Editi = find (Paper, Edition); 
     Pagen = find (Paper, Page); 
     Bookt = find (Paper, BookTitle); 
     Years = find (Paper, Year);   
     Editl = find (Paper, EditorList); 
     Authl = find (Paper, AuthorList); 

     Matcher mEdito = Editor.matcher(Editl); 
     Edito = mEdito.group(1); 
     while (mEdito.find()) // while loop to find all editors 
     { 
      System.out.println("Searching editors");     
      Foren = find (Edito, ForeName); 
      Initi = find (Edito, Initials); 
      Lastn = find (Edito, LastName); 
      System.out.println ("EDITORS: " + Bookt + "\t" + Foren + "\t" + Initi + "\t" + Lastn); 
     } 
     Matcher mAutho = Author.matcher(Authl); 
     while (mAutho.find()) // while loop to find all editors 
     { 
      System.out.println("Searching authors"); 
      Autho = mAutho.group(1); 
      Foren = find (Autho, ForeName); 
      Initi = find (Autho, Initials); 
      Lastn = find (Autho, LastName); 
      System.out.println ("AUTHORS: " + Bookt + "\t" + Foren + "\t" + Initi + "\t" + Lastn); 
     } 
    } 
} 

public static void main(String[] args) throws IOException 
{ 
    readBook ("CC_book.txt"); //opens text file to be mined 


    //Start reading Colon Cancer Book Information 

    //Start reading Endocrine Cancer Book Information 

    //Start reading Lung Cancer Book Information 

    //Start reading Other Cancer Book Information 

    //Start reading Pancreatic Cancer Book Information 
    scanner.close(); 
} 

}

Вот примеры данные из файла:

<PaperTitle>True incidence of all complications following immediate and delayed breast  reconstruction.</PaperTitle> 
<Abstract>BACKGROUND: Improved self-image and psychological well-being after breast  reconstruction are well documented. To determine methods that optimized results with minimal morbidity, the authors examined their results and complications based on reconstruction method and timing. METHODS: The authors reviewed all breast reconstructions after mastectomy for breast cancer performed under the supervision of a single surgeon over a 6-year period at a tertiary referral center. Reconstruction method and timing, patient characteristics, and complication rates were reviewed. RESULTS: Reconstruction was performed on 240 consecutive women (94 bilateral and 146 unilateral; 334 total reconstructions). Reconstruction timing was evenly split between immediate (n = 167) and delayed (n = 167). Autologous tissue (n = 192) was more common than tissue expander/implant reconstruction (n = 142), and the free deep inferior epigastric perforator was the most common free flap (n = 124). The authors found no difference in the complication incidence with autologous reconstruction, whether performed immediately or delayed. However, there was a significantly higher complication rate following immediate placement of a tissue expander when compared with delayed reconstruction (p = 0.008). Capsular contracture was a significantly more common late complication following immediate (40.4 percent) versus delayed (17.0 percent) reconstruction (p &lt; 0.001; odds ratio, 5.2; 95 percent confidence interval, 2.3 to 11.6). CONCLUSIONS: Autologous reconstruction can be performed immediately or delayed, with optimal aesthetic outcome and low flap loss risk. However, the overall complication and capsular contracture incidence following immediate tissue expander/implant reconstruction was much higher than when performed delayed. Thus, tissue expander placement at the time of mastectomy may not necessarily save the patient an extra operation and may compromise the final aesthetic outcome.</Abstract> 
<BookTitle>Book1</BookTitle> 
<Publisher>Publisher01, Boston</Publisher> 
<Edition>1st</Edition> 
<EditorList> 
<Editor> 
    <LastName>Lewis</LastName> 
    <ForeName>Philip M</ForeName> 
    <Initials>PM</Initials> 
</Editor> 
<Editor> 
    <LastName>Kiffer</LastName> 
    <ForeName>Michael</ForeName> 
    <Initials>M</Initials> 
</Editor> 
</EditorList> 
<Page>19-28</Page> 
<Year>2008</Year> 
<AuthorList> 
      <Author ValidYN="Y"> 
       <LastName>Sullivan</LastName> 
       <ForeName>Stephen R</ForeName> 
       <Initials>SR</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Fletcher</LastName> 
       <ForeName>Derek R D</ForeName> 
       <Initials>DR</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Isom</LastName> 
       <ForeName>Casey D</ForeName> 
       <Initials>CD</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Isik</LastName> 
       <ForeName>F Frank</ForeName> 
       <Initials>FF</Initials> 
      </Author> 
</AuthorList> 
// 
<PaperTitle>Polygenes, risk prediction, and targeted prevention of breast cancer.</PaperTitle> 
<Abstract>BACKGROUND: New developments in the search for susceptibility alleles in complex disorders provide support for the possibility of a polygenic approach to the prevention and treatment of common diseases. METHODS: We examined the implications, both for individualized disease prevention and for public health policy, of findings concerning the risk of breast cancer that are based on common genetic variation. RESULTS: Our analysis suggests that the risk profile generated by the known, common, moderate-risk alleles does not provide sufficient discrimination to warrant individualized prevention. However, useful risk stratification may be possible in the context of programs for disease prevention in the general population. CONCLUSIONS: The clinical use of single, common, low-penetrance genes is limited, but a few susceptibility alleles may distinguish women who are at high risk for breast cancer from those who are at low risk, particularly in the context of population screening.</Abstract> 
<BookTitle>Book2</BookTitle> 
<Publisher>Publisher02, New York</Publisher> 
<Edition>3rd</Edition> 
<EditorList> 
<Editor> 
    <LastName>Bernstein</LastName> 
    <ForeName>Arthur</ForeName> 
    <Initials>A</Initials> 
</Editor> 
</EditorList> 
<Page>2796-803</Page> 
<Year>2008</Year> 
<AuthorList> 
      <Author ValidYN="Y"> 
       <LastName>Pharoah</LastName> 
       <ForeName>Paul D P</ForeName> 
       <Initials>PD</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Antoniou</LastName> 
       <ForeName>Antonis C</ForeName> 
       <Initials>AC</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Easton</LastName> 
       <ForeName>Douglas F</ForeName> 
       <Initials>DF</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Ponder</LastName> 
       <ForeName>Bruce A J</ForeName> 
       <Initials>BA</Initials> 
      </Author> 
</AuthorList> 
// 
<PaperTitle>Invasive breast cancer: predicting disease recurrence by using high-spatial-resolution signal enhancement ratio imaging.</PaperTitle> 
<Abstract>PURPOSE: To retrospectively evaluate high-spatial-resolution signal enhancement ratio (SER) imaging for the prediction of disease recurrence in patients with breast cancer who underwent preoperative magnetic resonance (MR) imaging. MATERIALS AND METHODS: This retrospective study was approved by the institutional review board and was HIPAA compliant; informed consent was waived. From 1995 to 2002, gadolinium-enhanced MR imaging data were acquired with a three time point high-resolution method in women undergoing neoadjuvant therapy for invasive breast cancers. Forty-eight women (mean age, 49.1 years; range, 29.7-72.4 years) were divided into recurrence-free or recurrence groups. Volume measurements were tabulated for SER values between set ranges; cutoff criteria were defined to predict disease recurrence after surgery. Wilcoxon rank sum tests and the multivariate Cox proportional hazards regression model were used for evaluation. RESULTS: Breast tumor volume calculated from the number of voxels with SER values above a threshold corresponding to the upper limit of mean redistribution rate constant in benign tumors (0.88 minutes(-1)) and the volume of cancerous breast tissue infiltrating into the parenchyma were important predictors of disease recurrence. Seventy-five percent of patients with recurrence and 100% of deceased patients were identified as being at high risk for recurrence. Thirty percent of patients with recurrence and 67% of deceased patients were identified as having high risk before chemotherapy. No patients in the recurrence-free group were misidentified as likely to have recurrence. All three prechemotherapy parameters (total tumor volume, tumor volumes with high and low SER) and the postchemotherapy tumor volume with high SER were significantly different between the two groups. The multivariate Cox proportional hazards regression showed that, of the three prechemotherapy covariates, only the low SER and high SER tumor volumes (P = .017 and .049, respectively) were significant and independent predictors of tumor recurrence. Tumor volume with high SER was the only significant postchemotherapy covariate predictor (P = .038). CONCLUSION: High-spatial-resolution SER imaging may improve prediction for patients at high risk for disease recurrence and death.</Abstract> 
<BookTitle>Book3</BookTitle> 
<Publisher>Publisher03, London</Publisher> 
<Edition>3rd</Edition> 
<EditorList> 
<Editor> 
    <LastName>Anderson</LastName> 
    <ForeName>John T</ForeName> 
    <Initials>JT</Initials> 
</Editor> 
<Editor> 
    <LastName>Hoffman</LastName> 
    <ForeName>John A</ForeName> 
    <Initials>JA</Initials> 
</Editor> 
<Editor> 
    <LastName>Smithson</LastName> 
    <ForeName>Joshua H</ForeName> 
    <Initials>JH</Initials> 
</Editor> 
</EditorList> 
<Page>79-87</Page> 
<Year>2008</Year> 
<AuthorList> 
      <Author ValidYN="Y"> 
       <LastName>Li</LastName> 
       <ForeName>Ka-Loh</ForeName> 
       <Initials>KL</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Partridge</LastName> 
       <ForeName>Savannah C</ForeName> 
       <Initials>SC</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Joe</LastName> 
       <ForeName>Bonnie N</ForeName> 
       <Initials>BN</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Gibbs</LastName> 
       <ForeName>Jessica E</ForeName> 
       <Initials>JE</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Lu</LastName> 
       <ForeName>Ying</ForeName> 
       <Initials>Y</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Esserman</LastName> 
       <ForeName>Laura J</ForeName> 
       <Initials>LJ</Initials> 
      </Author> 
      <Author ValidYN="Y"> 
       <LastName>Hylton</LastName> 
       <ForeName>Nola M</ForeName> 
       <Initials>NM</Initials> 
      </Author> 
</AuthorList> 
// 
+0

Правильно ли работает ваш сканер. Сколько циклов он делает? Не уверен в этом \\ // разделителе. Не должно быть \ \ \/ – Phil

+0

Сканер отлично работает для первых 9 совпадений в первом цикле. В отдельной проверке разделитель работал в отформатированном виде. Файл имеет «//», разделяющий каждую статью. – BigData

+1

Анализ XML с помощью регулярных выражений ...: -/почему не использовать синтаксический анализатор XML? – Jesper

ответ

1

Я знаю, что Java должен иметь множество инструментов для разбора XML и разбора XML с регулярными выражениями, на вершине многих вещей , может стать довольно грязным.


Я не программист на Java, но вы, вероятно, сталкиваетесь. по умолчанию не соответствует новой строке. Вы можете прикрепить все свои регулярные выражения с помощью переключателя (?s), который действительно относится только к редактору, автору, редактору и автору.

Например, авторское выражение regex будет выглядеть примерно так.

static Pattern Author = Pattern.compile("(?s)<Author>(.+?)</Author>"); 

Источник:Regular expression does not match newline obtained from Formatter object


Как-то вы прокомментировали

... Это еще одна проблема, так как если он пустой, он должен просто вернуть другую пустую строку , ...

Причина, по которой ваши регулярные выражения не будут делать этого, заключается в том, что вы используете (. +?). Если вы измените каждое вхождение этого, где это применимо, на (.*?), то вы разрешите пустые строки. . + требуется символ (любой символ) между тегами открытия и закрытия. . * не требует персонажа, но хватает любого присутствующего. И? делает совпадение не-жадным, поэтому оно фиксируется, как только оно соответствует критериям.

Consider the string: I like cats, I wonder if you like cats 
"I (.*) cats" matches the whole string. 
"I (.*?) cats" matches "I like cats", and if the global flag is on, seperately matches "I wonder if you like cats" 

Вы уверены, что AuthorList/EditorList является то, что это сбой?

Ваш Author regex не учитывает атрибут ValidYN, но каждый экземпляр в этом примере данных содержит его, поэтому вы должны соответствовать ему.

Для Author регулярных выражений попробовать

<Author(?: [\w\-]*="[^"]*")*>(.+?)</Author> 

Это простая модель, которая выглядит для атрибутов, которые содержат буквы, цифры, _ или дефис в атрибуте и в кавычках атрибута, который не может сам по себе содержит цитату.

Или, проще, если ValidYN единственный атрибут, вы encouter:

<Author ValidYN="(?:Y|N)">(.+?)</Author> 

Первое регулярное выражение, однако, может прийти в Handly для dealinng с другими тегами, которые могут иметь атрибуты, если этот вопрос должен возникают.

+0

Это следующая проблема в списке, но текущая проблема заключается в том, что список редакторов при поиске возвращает null. После списка редакторов он будет искать редакторов, затем список авторов, а затем для конкретных авторов. Программа аварийно завершает работу, пытаясь найти конкретные редакторы в пустой строке редактора. Это еще одна проблема, поскольку, если она пуста, она должна просто вернуть еще одну нулевую строку. – BigData

+0

@BigData Обновлен мой ответ, я считаю, что еще одна проблема заключается в том, что вы многострочный флаг не включен. –

+0

Я впервые внедрил изменение с + на *, но я не повлиял на результат. Я должен отметить, что хотя EditorList возвращает null, если я должен был инициализировать String, найденную чем-то другим (например: «Not Found!»), Тогда поиск также вернет это. Оба автора Regexes, которые вы предложили, помечены как содержащие несложные ошибки. Это спорный вопрос, так как класс не идет, что далеко в код, прежде чем врезаться в связи с отказа от ошибки границ, когда редакторы искали. – BigData

0

Любая группа может быть получена только после поиска (или соответствия или поиска).

Matcher mEdito = Editor.matcher(Editl); 
    Edito = mEdito.group(1); 
    while (mEdito.find()) // while loop to find all editors 
    { 

Должно быть

Matcher mEdito = Editor.matcher(Editl); 
    while (mEdito.find()) // while loop to find all editors 
    { 
     Edito = mEdito.group(1); 

P.S,

JAXB позволит это XML для чтения в объекты Java (классы Автор, редактор и т.д.).


Я видел, что вам нужно регулярное выражение ., чтобы соответствовать новой строки тоже. Это опция DOT_ALL, которая может быть записана в регулярном выражении как команда (?s) («одиночная строка»).

static Pattern EditorList = Pattern.compile("(?s)<EditorList>(.+?)</EditorList>"); 
... 
static Pattern AuthorList = Pattern.compile("(?s)<AuthorList>(.+?)</AuthorList>"); 
+0

Это не повлияло на код, но спасибо за помощь. У меня есть короткий период времени, чтобы узнать и реализовать код, регулярное выражение имеет больше смысла/было проще и быстрее узнать. В ретроспективе я должен был научиться разбирать xml – BigData

+0

Я подошел ближе и увидел, что регулярное выражение тоже не в порядке. –

 Смежные вопросы

  • Нет связанных вопросов^_^