用java分割字符串

use*_*881 0 java regex string indexof

我有两种类型的字符串

command1|Destination-IP|DestinationPort
Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message
Run Code Online (Sandbox Code Playgroud)

我试图拆分String以获取我开始编码的变量,但不确定这是最好的方法

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);
Run Code Online (Sandbox Code Playgroud)

我要继续这样吗?或者也许使用正则表达式?如果String是

command1|Destination-IP|DestinationPort
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,因为没有第三个 |

anu*_*ava 5

最好通过管道符号分割您的输入:

String[] tokens = sentence.split( "[|]" ); // or sentence.split( "\\|" )
Run Code Online (Sandbox Code Playgroud)

然后通过检查tokens.length并采取相应的行动来检查令牌数量.


Nig*_*nel 5

看一下String.split方法:

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

旁注:由于"|"字符"|"在正则表达式语法中具有特殊含义(基本上是指OR),因此应使用反斜杠对其进行转义.

实际上,查看非转义版本的结果非常有趣"first|second|third".split("|").

正则表达式"|"将英语翻译为"空字符串或空字符串",并在任何位置匹配字符串."first|second|third".split("|")返回长度为19的数组:{"", "f", "i", "r", ..., "d"}