解析管道分离的字符串

时间:2013-12-02 16:46:23

标签: java string parsing pipe

我使用以下代码来解析字符串:package org.datacontract;

public class TestParsing {


    public static void main(String[] args){
        String test = "6000FCI|6|22|122548";

        String[] result = test.split("\\|");

        for(String s : result){
            System.out.println(s);
        }
    }
}

我的输出是:

6000FCI
6
22
122548

如何只获取输出的第一个值: 6000FCI

1 个答案:

答案 0 :(得分:1)

如果你只需要第一个值并且你的输入很简单,那么不需要正则表达式,而是做一些更简单的事情:

test.substring(0, test.indexOf('|'));

这可以更有效地处理。否则,您只需访问结果数组的第一个索引处的值。

注意:如果test可能不包含管道,请执行此操作:

int index = test.indexOf('|');
String result = index == -1 ? test : test.substring(0, index);
相关问题