2014-01-22 49 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

谢谢!有用 –