我有一个像这样的字符串 -
"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 .....
最佳答案
您的分隔符不正确。您应该在每个 =
之后设置分隔符标志,并且也在每个 whitespace
。您可以直接使用它:-
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 ....
关于java - 使用扫描仪打印标记和分隔符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614180/