我有兩種類型的字符串斯普利特用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
因爲有我得到一個錯誤,沒有第三|
'myStr.split(「\\ |」);''或'myStr.split(Pattern.quote(「|」));'。 – Maroun
您也可以使用[StringUtils.split]之一(http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang。字符串))方法從Apache公共,例如'StringUtils.split(sentence,'|')' –