2014-01-26 111 views
0

我有兩種類型的字符串斯普利特用java字符串

command1|Destination-IP|DestinationPort 
Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message 

的我試圖分割字符串得到變量 我開始編碼這樣的,但不知道它是最好的方式

public String dstIp=""; 
    public String dstPort=""; 
    public String srcIp=""; 
    public String scrPort=""; 
    public String message=""; 
    public String command=""; 

int first = sentence.indexOf ("|"); 


       if (first > 0) 
       { 

        int second = sentence.indexOf("|", first + 1); 
        int third = sentence.indexOf("|", second + 1); 

       command = sentence.substring(0,first); 
       dstIp= sentence.substring(first+1,second); 
       dstPort= sentence.substring(second+1,third); 

我應該繼續這樣嗎?或者可能使用正則表達式? 如果字符串是

command1|Destination-IP|DestinationPort 

因爲有我得到一個錯誤,沒有第三|

+2

'myStr.split(「\\ |」);''或'myStr.split(Pattern.quote(「|」));'。 – Maroun

+0

您也可以使用[StringUtils.split]之一(http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang。字符串))方法從Apache公共,例如'StringUtils.split(sentence,'|')' –

回答

5

更好的分裂由管道符號在這裏你輸入:

String[] tokens = sentence.split("[|]"); // or sentence.split("\\|") 

然後檢查令牌#通過檢查tokens.length並採取相應措施。

0

使用Java函數split(),它可以精確地管理你正在尋找的東西!

示例代碼:

String test = "bla|blo|bli"; 
String[] result = test.split("\\|"); 
+0

您也可以使用搜索功能:請參閱http://stackoverflow.com/questions/2198373/java-how-to-split-a-string-on-加號 – PrR3

0

split使用與\\|作爲參數。它返回一個String[],它將包含| -split字符串的不同部分。

+1

不,'''應該逃脫。 – Maroun

5

看看在String.split方法:

String line = "first|second|third"; 
String[] splitted = line.split("\\|"); 
for (String part: splitted) { 
    System.out.println(part); 
} 

旁註:因爲"|"字符在正則表達式syntax特殊含義(基本上"|"手段OR),應該用反斜槓轉義。

實際上,查看非轉義版本"first|second|third".split("|")的結果是非常有趣的。

正則表達式"|"將英文翻譯爲「空字符串或空字符串」,並在任意位置匹配字符串"first|second|third".split("|")返回一個長度爲19的數組:{"", "f", "i", "r", ..., "d"}