1

here の別の質問のおかげで、必要なものをほとんど手に入れましたが、完全ではありません。

Java の String.split() を使用して文字列を分割し、正規表現の区切り記号を保持しようとしています。私の区切り文字は単一の文字ではありません。例:

hello {world} this is {stack overflow} and this is my string

次のような配列に分割する必要があります。

hello

{world}

this is

{stack overflow}

and this is my string

{ と } の間のすべてのテキストを一致{[^}]+}させ、それを使用して文字列を分割できます。しかし、テキストを { と } の間にも保持する必要があります。

4

1 に答える 1

9

このように分割してみてください

yourString.split("\\s(?=\\{)|(?<=\\})\\s")

それは、その後にあるすべてのスペース{、またはその}前にあるスペースで分割されます。


デモ

for (String s : "hello {world} this is {stack overflow} and this is my string"
        .split("\\s(?=\\{)|(?<=\\})\\s")) 
    System.out.println(s);

出力

hello
{world}
this is
{stack overflow}
and this is my string
于 2013-06-04T00:16:50.147 に答える