2016-12-02 95 views
0

我有以下字符串输入(从netstat -a命令):解析没有忽略空格 - Java的

Proto RefCnt Flags  Type  State   I-Node Path 
unix 2  [ ]   DGRAM     11453 /run/systemd/shutdownd 
unix 2  [ ]   DGRAM     7644  /run/systemd/notify 
unix 2  [ ]   DGRAM     7646  /run/systemd/cgroups-agent 
unix 5  [ ]   DGRAM     7657  /run/systemd/journal/socket 
unix 14  [ ]   DGRAM     7659  /dev/log 
unix 3  [ ]   STREAM  CONNECTED  16620 
unix 3  [ ]   STREAM  CONNECTED  16621 

同时我试图分析上面的字符串:

// lines is an array representing each line above 
for (int i = 0; i < lines.length; i++) { 
    String[] tokens = lines[i].split("\\s+"); 
} 

我想将tokens作为7个条目[Proto, RefCnt, Flag, Type, State, I-Node, Path]的数组。相反,我得到排除Flags下架和空State数组:我怎样才能解决我的正则表达式来产生正确输出的

["unix", "2", "[", "]", "DGRAM", "11453", "/run/systemd/shutdownd"] 

代替

["unix", "2", "[]", "DGRAM", "", "11453", "/run/systemd/shutdownd"] 

+1

使用lookarounds' (?<!\ [)\\ s +(?!\))' – revo

+0

@revo即使在lookaround中也有一个值缺失(对于状态,数组长度将是6而不是7) – cybertextron

回答

1

你需要在你的正则表达式来设置最小间隔长度,2,尽量拆分这样的:

String[] tokens = lines[i].split("\\s{2,16}+"); 

或者使用类似@revo表明lookarounds,像这样:

String[] tokens = lines[i].split("(?<!\\[)\\s{2,16}+(?!\\])"); 
+0

Alexander,缺少一个值, 'm得到以下输出:'[unix,2,[],DGRAM,11453,/ run/systemd/shutdownd]'。正确的值将是'[unix,2,[],DGRAM,“”,11453,/ run/systemd/shutdownd]' – cybertextron

+1

@cybertextron您也可以添加maximun space legth,就像这个'{2,16} –