1

私はこのような文字列を持っています -

"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 .....
4

1 に答える 1

1

区切り文字が正しくありません。=各記号の後に区切り文字を設定する必要があります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ここが必要です。さらに、分割を 2 回行う必要があります。1 回は空白で、もう 1 回は=.

=ここで、値に含まれる空白を誤って分割しないように、空白の後に で終わる一連のアルファベットを続ける必要があります。したがって、コードは次のようになります。

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 ....
于 2013-01-30T21:37:29.383 に答える