我有一个像这样的字符串 -
"fruit=apple man=human abc=123"
我希望将值打印为 -
fruit=
apple
man=
human
abc=
123
即。我也想查看分隔符值。目前我正在尝试 -
String status2="fruit=apple man=human abc=123";
Scanner scn = new Scanner(status2).useDelimiter("[a-z]*=+");
while(scn.hasNext())
{
System.out.println(scn.next());
System.out.println(scn.delimiter());
}
但是我看不到分隔符值
apple
[a-z]*=+
human
[a-z]*=+
123
[a-z]*=+
更新字符串 -
"cobdate=01/28/2013 fundsnotextracted= elapsedtime=00:06:02 user=dataprod starttime=Wed, 30 Jan 2013 11:50:30 periods=DAILY, MTD, YTD knowledgedate=01/30/2013:11:50:10 progress=67 statusstep=Generating Reports ....."
预期输出
cobdate=01/28/2013
fundsnotextracted=
elapsedtime=00:06:02
user=dataprod
starttime=Wed, 30 Jan 2013 11:50:30
periods=DAILY, MTD, YTD
knowledgedate=01/30/2013:11:50:10
progress=67
statusstep=Generating Reports .....
答案 0 :(得分:1)
您的分隔符不正确。您应该在每个=
符号后以及每个whitespace
设置分隔符。您可以使用此insead: -
Scanner scn = new Scanner(status2).useDelimiter("(?<==)|[ ]");
此处的分隔符为: - =
表示的每个(?<==)
后面的空字符串或[ ]
表示的空格。
但是,根据您的输入字符串和所需的输出,我希望split
字符串,与我在pattern
中使用的delimiter
相同,这将给您一个数组,以后你也可以在其他地方使用: -
String status2="fruit=apple man=human abc=123";
String[] arr = status2.split("(?<==)|[ ]");
System.out.println(Arrays.toString(arr));
更新: -
对于您的更新输入,您将需要做更多的工作。首先,您在此处严格需要split
。另外,你必须进行两次拆分 - 一次在空格上,另一次放在=
上。
现在,您的空白后面必须跟一系列以=
结尾的字母表,这样您就不会错误地拆分值中包含的空格。因此,您的代码应如下所示: -
String str = "cobdate=01/28/2013 fundsnotextracted= elapsedtime=00:06:02 user=dataprod starttime=Wed, 30 Jan 2013 11:50:30 periods=DAILY, MTD, YTD knowledgedate=01/30/2013:11:50:10 progress=67 statusstep=Generating Reports .....";
// Split on a whitespace, followed by a sequence of letters ending with =.
// This ensures that you don't split on whitespace, optionally present in some values
String[] arr = str.split("[ ](?=[a-zA-Z]+=)");
for (String eachString : arr) {
// Split on empty string following the = sign
String[] tempArr = eachString.split("(?<==)");
System.out.print(tempArr[0] + " ");
// To ensure that you don't print a non-existence value.
if (tempArr.length == 2) {
System.out.println(tempArr[1]);
} else {
System.out.println();
}
}
输出: -
cobdate= 01/28/2013
fundsnotextracted=
elapsedtime= 00:06:02
user= dataprod
starttime= Wed, 30 Jan 2013 11:50:30
periods= DAILY, MTD, YTD
knowledgedate= 01/30/2013:11:50:10
progress= 67
statusstep= Generating Reports ....