我使用以下代码来解析字符串: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
答案 0 :(得分:1)
如果你只需要第一个值并且你的输入很简单,那么不需要正则表达式,而是做一些更简单的事情:
test.substring(0, test.indexOf('|'));
这可以更有效地处理。否则,您只需访问结果数组的第一个索引处的值。
注意:如果test
可能不包含管道,请执行此操作:
int index = test.indexOf('|');
String result = index == -1 ? test : test.substring(0, index);