2009-06-16 89 views
1

我有口一些C#代碼,Java和我有一些麻煩轉換爲字符串分割命令。C#正則表達式拆分爲Java模式分裂

雖然實際的正則表達式仍然是正確的,在分割時C#正則表達式令牌生成的字符串[]的一部分,但在Java正則表達式的令牌被去除。

什麼是保持分裂令牌上最簡單的方法?

下面是C#代碼工作我想要的方式爲例:

using System; 

using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main() 
    { 
     String[] values = Regex.Split("5+10", @"([\+\-\*\(\)\^\\/])"); 

     foreach (String value in values) 
      Console.WriteLine(value); 
    } 
} 

Produces: 
5 
+ 
10 
+4

你能給我們一個例子,你的輸入和正在使用的正則表達式分裂嗎? – 2009-06-16 17:43:38

+0

作爲一般說明,我很確定在一個字符類(方括號,「[]」)內部,你不需要太多反斜槓。其他人可以確認嗎? – 2009-06-16 18:07:20

回答

1

我不知道C#怎麼做的,但要實現它在Java中,你必須接近它。看看如何this code它:

public String[] split(String text) { 
    if (text == null) { 
     text = ""; 
    } 

    int last_match = 0; 
    LinkedList<String> splitted = new LinkedList<String>(); 

    Matcher m = this.pattern.matcher(text); 

    // Iterate trough each match 
    while (m.find()) { 
     // Text since last match 
     splitted.add(text.substring(last_match,m.start())); 

     // The delimiter itself 
     if (this.keep_delimiters) { 
      splitted.add(m.group()); 
     } 

     last_match = m.end(); 
    } 
    // Trailing text 
    splitted.add(text.substring(last_match)); 

    return splitted.toArray(new String[splitted.size()]); 
} 
1

這是因爲你捕捉分裂令牌。 C#將此作爲提示,希望將該標記本身保留爲結果數組的成員。 Java不支持這一點。