2009-05-27 64 views
37

我使用split()來標記以下這種格式與*分隔的字符串:符號化錯誤:java.util.regex.PatternSyntaxException,晃來晃去的元字符「*」

name*lastName*ID*school*age 
% 
name*lastName*ID*school*age 
% 
name*lastName*ID*school*age 

我從一個指定的文件閱讀本「entrada.al」 使用此代碼:

static void leer() { 

    try { 
     String ruta="entrada.al"; 
     File myFile = new File (ruta); 
     FileReader fileReader = new FileReader(myFile); 

     BufferedReader reader = new BufferedReader(fileReader); 

     String line = null; 

     while ((line=reader.readLine())!=null){ 
      if (!(line.equals("%"))){ 
       String [] separado = line.split("*"); //SPLIT CALL 
       names.add(separado[0]); 
       lastNames.add(separado[1]); 
       ids.add(separado[2]); 
       ages.add(separado[3]); 
      } 
     } 

     reader.close(); 
    } 

而且我得到這個異常:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 *

我的猜測是在原始文本文件的年齡之後缺少*正在導致此問題。我如何解決它?

回答

118

不,問題在於*是正則表達式中的保留字符,所以您需要將其轉義。

String [] separado = line.split("\\*"); 

*意味着「零個或多個前面的表達式」(見Pattern Javadocs),而你不給它任何先前的表現,讓您的分裂表達非法的。這就是爲什麼錯誤是PatternSyntaxException

3

第一個答案涵蓋了它。

我猜你可能會決定將你的信息存儲在不同的類/結構中。在這種情況下,你可能不希望結果從split()方法進入數組。

你沒有要求它,但我很無聊,所以這裏是一個例子,希望它有幫助。

,這可能是你寫來表示一個人的類:

 

class Person { 
      public String firstName; 
      public String lastName; 
      public int id; 
      public int age; 

     public Person(String firstName, String lastName, int id, int age) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.id = id; 
     this.age = age; 
     } 
     // Add 'get' and 'set' method if you want to make the attributes private rather than public. 
} 
 

然後,版本,最初發布將是這個樣子的解析代碼: (此將它們存儲在一個LinkedList,你可以用別的東西像一個Hashtable,等等。)

 

try 
{ 
    String ruta="entrada.al"; 
    BufferedReader reader = new BufferedReader(new FileReader(ruta)); 

    LinkedList<Person> list = new LinkedList<Person>(); 

    String line = null;   
    while ((line=reader.readLine())!=null) 
    { 
     if (!(line.equals("%"))) 
     { 
      StringTokenizer st = new StringTokenizer(line, "*"); 
      if (st.countTokens() == 4)   
       list.add(new Person(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken)));   
      else    
       // whatever you want to do to account for an invalid entry 
        // in your file. (not 4 '*' delimiters on a line). Or you 
        // could write the 'if' clause differently to account for it   
     } 
    } 
    reader.close(); 
} 
 
2

這是因爲*被用作元字符來表示一個字符中的一個或多個字符的字符串。所以如果我寫M *,那麼它會查找文件MMMMMM .....!這裏你使用*作爲唯一的字符,所以編譯器正在尋找字符來查找多個事件,所以它會拋出異常。:)

5

我有類似的問題regex = "?"。它發生在所有在正則表達式中都有一定含義的特殊字符。所以你需要有"\\"作爲你的正則表達式的前綴。

String [] separado = line.split("\\*");