2010-09-09 39 views
0

我試圖把存儲這種形式的數據文件:如何創建一個數組來存儲java中的正則表達式字符串匹配?

Name=」Biscuit」 

LatinName=」Retrieverus Aurum」 

ImageFilename=」Biscuit.png」 

DNA=」ITAYATYITITIAAYI」 

,並用正則表達式來找到有用的信息裏看到了。即字段及其內容。

我已經創建了正則表達式,但我似乎只能在任何給定的時間獲得一個匹配,並且希望將文件中每行的每個匹配項放在它們自己的字符串索引中。

這是我到目前爲止有:

Scanner scanFile = new Scanner(file); 
     while (scanFile.hasNextLine()){ 
      System.out.println(scanFile.findInLine(".*")); 
      scanFile.nextLine(); 
     } 
     MatchResult result = null; 
     scanFile.findInLine(Constants.ANIMAL_INFO_REGEX); 
     result = scanFile.match(); 


     for (int i=1; i<=result.groupCount(); i++){ 
      System.out.println(result.group(i)); 
      System.out.println(result.groupCount()); 
     } 
     scanFile.close(); 
     MySpecies species = new MySpecies(null, null, null, null); 
     return species; 

非常感謝您的幫助!

+0

它很可能是有用的,包括你的如果問題出在那裏,也是正則表達式。 – Shadwell 2010-09-09 23:46:13

+0

[我的正則表達式導致Java中的堆棧溢出;我錯過了什麼?](http://stackoverflow.com/questions/3681928/my-regex-is-causing-a-stack-overflow-in-java-what-am--missing) – 2010-09-10 07:12:05

回答

0

我希望我正確地理解你的問題......這是從Oracle網站未來的一個例子:

/* 
* This code writes "One dog, two dogs in the yard." 
* to the standard-output stream: 
*/ 
import java.util.regex.*; 

public class Replacement { 
    public static void main(String[] args) 
         throws Exception { 
     // Create a pattern to match cat 
     Pattern p = Pattern.compile("cat"); 
     // Create a matcher with an input string 
     Matcher m = p.matcher("one cat," + 
         " two cats in the yard"); 
     StringBuffer sb = new StringBuffer(); 
     boolean result = m.find(); 
     // Loop through and create a new String 
     // with the replacements 
     while(result) { 
      m.appendReplacement(sb, "dog"); 
      result = m.find(); 
     } 
     // Add the last segment of input to 
     // the new String 
     m.appendTail(sb); 
     System.out.println(sb.toString()); 
    } 
} 

希望這有助於...

+0

不,這不會根本不適用。 – 2010-09-10 11:12:50