2014-01-22 46 views
0

我會盡力在我的解釋中明確^ ^。我輸入一個文本,我逐行閱讀文件(我一直一字一句地嘗試)。有一次,我看我申請一個正則表達式的工作,但輸出文件不適合我,我得到這個類型的輸出:在線上提取多個標籤

<pers> Sarkozy </pers> 
<pers> Muscat </pers> , le secrétaire général , devant <pers> Sarkozy </pers> 
<pers> Muscat </pers> 

我會想:

<pers> Sarkozy </pers> 
<pers> Muscat </pers> 
<pers> Sarkozy </pers> 
<pers> Muscat </pers> 

我能不明白的地方這個問題......我覺得從它匹配我的模式的那一刻起,我需要在整條線上劃一條線,而不僅僅是標籤......我的正則表達式是不是很好,或者是我的方式讀我的文件?

我的代碼:

public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 

     File file = new File(
       monfichier); 
     String fileContent = readFileAsString(file.getAbsolutePath()); 

     countNE countne = new countNE(); 

     String result = countne.countNE(fileContent); 
     System.out.println(result); 


    } 

    public String countNE(String fileContent) throws java.io.IOException { 
     int i = 0; 
     Hashtable<String, Integer> table = new Hashtable(); 
     int nbOcc = 0; 

     String regPerson = "<pers>.?\\w*.?</pers>"; 

     Pattern pPers = Pattern.compile(regPerson); 

     Matcher m = pPers.matcher(fileContent); 
     String result = ""; 

     while (m.find()) { 
      String person = m.group(); 
      // System.out.println(person + " " + i); 
      // System.out.println(person); 
      i++; 
      result += person + "\n"; 
     } 
     return result; 

    } 

    public static String readFileAsString(String filePath) 
      throws java.io.IOException { 
     String chaine = ""; 
     // lecture du fichier texte 
     try { 
      InputStream ips = new FileInputStream(filePath); 
      InputStreamReader ipsr = new InputStreamReader(ips); 
      BufferedReader br = new BufferedReader(ipsr); 
      String ligne; 
      while ((ligne = br.readLine()) != null) { 
       chaine += ligne + "\n"; 

      } 
      br.close(); 
     } catch (Exception e) { 
      System.out.println(e.toString()); 
     } 

     System.out.println(chaine); 
     return chaine; 
    } 

} 

感謝您的幫助

+0

的正則表達式是不是這個。你有沒有考慮嵌套標籤?改用解析器。 – m0skit0

+0

您可以將您的代碼從文件讀取轉換爲僅使用硬編碼字符串(因此我們可以有一個容易重現的示例)?使用'StringReader'應該使這個改變變得很簡單。 – Dukeling

回答

0

的問題是

.? 
在您的正則


它匹配任何東西,包括<pers></pers>
因此,爲了得到你想要的東西,你可能首先分割線向上或者通過使用字符的短間隔爲匹配(例如[a-zA-Z]或類似)排除.<pers>

+0

'。?'是單個可選字符,因此它不能匹配''或''。 – Dukeling

0

正確的做法:

public static String countNE(String fileContent) throws java.io.IOException { 
    Hashtable<String, Integer> table = new Hashtable(); 
    int nbOcc = 0; 

    String regPerson = "(<pers>.*?</pers>)"; 
    // String regPerson = "(<.*>.*?</.*>)"; 

    Pattern pPers = Pattern.compile(regPerson); 

    Matcher m = pPers.matcher(fileContent); 
    String result = ""; 
    while(m.find()) 
    { 
      result += m.group(1); 
    } 

    return result; 
} 
+0

謝謝!有用 –